菜谱项目

DocParser.php 39KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191
  1. <?php
  2. /*
  3. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14. *
  15. * This software consists of voluntary contributions made by many individuals
  16. * and is licensed under the MIT license. For more information, see
  17. * <http://www.doctrine-project.org>.
  18. */
  19. namespace Doctrine\Common\Annotations;
  20. use Doctrine\Common\Annotations\Annotation\Attribute;
  21. use ReflectionClass;
  22. use Doctrine\Common\Annotations\Annotation\Enum;
  23. use Doctrine\Common\Annotations\Annotation\Target;
  24. use Doctrine\Common\Annotations\Annotation\Attributes;
  25. /**
  26. * A parser for docblock annotations.
  27. *
  28. * It is strongly discouraged to change the default annotation parsing process.
  29. *
  30. * @author Benjamin Eberlei <kontakt@beberlei.de>
  31. * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
  32. * @author Jonathan Wage <jonwage@gmail.com>
  33. * @author Roman Borschel <roman@code-factory.org>
  34. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  35. * @author Fabio B. Silva <fabio.bat.silva@gmail.com>
  36. */
  37. final class DocParser
  38. {
  39. /**
  40. * An array of all valid tokens for a class name.
  41. *
  42. * @var array
  43. */
  44. private static $classIdentifiers = array(
  45. DocLexer::T_IDENTIFIER,
  46. DocLexer::T_TRUE,
  47. DocLexer::T_FALSE,
  48. DocLexer::T_NULL
  49. );
  50. /**
  51. * The lexer.
  52. *
  53. * @var \Doctrine\Common\Annotations\DocLexer
  54. */
  55. private $lexer;
  56. /**
  57. * Current target context.
  58. *
  59. * @var integer
  60. */
  61. private $target;
  62. /**
  63. * Doc parser used to collect annotation target.
  64. *
  65. * @var \Doctrine\Common\Annotations\DocParser
  66. */
  67. private static $metadataParser;
  68. /**
  69. * Flag to control if the current annotation is nested or not.
  70. *
  71. * @var boolean
  72. */
  73. private $isNestedAnnotation = false;
  74. /**
  75. * Hashmap containing all use-statements that are to be used when parsing
  76. * the given doc block.
  77. *
  78. * @var array
  79. */
  80. private $imports = array();
  81. /**
  82. * This hashmap is used internally to cache results of class_exists()
  83. * look-ups.
  84. *
  85. * @var array
  86. */
  87. private $classExists = array();
  88. /**
  89. * Whether annotations that have not been imported should be ignored.
  90. *
  91. * @var boolean
  92. */
  93. private $ignoreNotImportedAnnotations = false;
  94. /**
  95. * An array of default namespaces if operating in simple mode.
  96. *
  97. * @var string[]
  98. */
  99. private $namespaces = array();
  100. /**
  101. * A list with annotations that are not causing exceptions when not resolved to an annotation class.
  102. *
  103. * The names must be the raw names as used in the class, not the fully qualified
  104. * class names.
  105. *
  106. * @var bool[] indexed by annotation name
  107. */
  108. private $ignoredAnnotationNames = array();
  109. /**
  110. * A list with annotations in namespaced format
  111. * that are not causing exceptions when not resolved to an annotation class.
  112. *
  113. * @var bool[] indexed by namespace name
  114. */
  115. private $ignoredAnnotationNamespaces = array();
  116. /**
  117. * @var string
  118. */
  119. private $context = '';
  120. /**
  121. * Hash-map for caching annotation metadata.
  122. *
  123. * @var array
  124. */
  125. private static $annotationMetadata = array(
  126. 'Doctrine\Common\Annotations\Annotation\Target' => array(
  127. 'is_annotation' => true,
  128. 'has_constructor' => true,
  129. 'properties' => array(),
  130. 'targets_literal' => 'ANNOTATION_CLASS',
  131. 'targets' => Target::TARGET_CLASS,
  132. 'default_property' => 'value',
  133. 'attribute_types' => array(
  134. 'value' => array(
  135. 'required' => false,
  136. 'type' =>'array',
  137. 'array_type'=>'string',
  138. 'value' =>'array<string>'
  139. )
  140. ),
  141. ),
  142. 'Doctrine\Common\Annotations\Annotation\Attribute' => array(
  143. 'is_annotation' => true,
  144. 'has_constructor' => false,
  145. 'targets_literal' => 'ANNOTATION_ANNOTATION',
  146. 'targets' => Target::TARGET_ANNOTATION,
  147. 'default_property' => 'name',
  148. 'properties' => array(
  149. 'name' => 'name',
  150. 'type' => 'type',
  151. 'required' => 'required'
  152. ),
  153. 'attribute_types' => array(
  154. 'value' => array(
  155. 'required' => true,
  156. 'type' =>'string',
  157. 'value' =>'string'
  158. ),
  159. 'type' => array(
  160. 'required' =>true,
  161. 'type' =>'string',
  162. 'value' =>'string'
  163. ),
  164. 'required' => array(
  165. 'required' =>false,
  166. 'type' =>'boolean',
  167. 'value' =>'boolean'
  168. )
  169. ),
  170. ),
  171. 'Doctrine\Common\Annotations\Annotation\Attributes' => array(
  172. 'is_annotation' => true,
  173. 'has_constructor' => false,
  174. 'targets_literal' => 'ANNOTATION_CLASS',
  175. 'targets' => Target::TARGET_CLASS,
  176. 'default_property' => 'value',
  177. 'properties' => array(
  178. 'value' => 'value'
  179. ),
  180. 'attribute_types' => array(
  181. 'value' => array(
  182. 'type' =>'array',
  183. 'required' =>true,
  184. 'array_type'=>'Doctrine\Common\Annotations\Annotation\Attribute',
  185. 'value' =>'array<Doctrine\Common\Annotations\Annotation\Attribute>'
  186. )
  187. ),
  188. ),
  189. 'Doctrine\Common\Annotations\Annotation\Enum' => array(
  190. 'is_annotation' => true,
  191. 'has_constructor' => true,
  192. 'targets_literal' => 'ANNOTATION_PROPERTY',
  193. 'targets' => Target::TARGET_PROPERTY,
  194. 'default_property' => 'value',
  195. 'properties' => array(
  196. 'value' => 'value'
  197. ),
  198. 'attribute_types' => array(
  199. 'value' => array(
  200. 'type' => 'array',
  201. 'required' => true,
  202. ),
  203. 'literal' => array(
  204. 'type' => 'array',
  205. 'required' => false,
  206. ),
  207. ),
  208. ),
  209. );
  210. /**
  211. * Hash-map for handle types declaration.
  212. *
  213. * @var array
  214. */
  215. private static $typeMap = array(
  216. 'float' => 'double',
  217. 'bool' => 'boolean',
  218. // allow uppercase Boolean in honor of George Boole
  219. 'Boolean' => 'boolean',
  220. 'int' => 'integer',
  221. );
  222. /**
  223. * Constructs a new DocParser.
  224. */
  225. public function __construct()
  226. {
  227. $this->lexer = new DocLexer;
  228. }
  229. /**
  230. * Sets the annotation names that are ignored during the parsing process.
  231. *
  232. * The names are supposed to be the raw names as used in the class, not the
  233. * fully qualified class names.
  234. *
  235. * @param bool[] $names indexed by annotation name
  236. *
  237. * @return void
  238. */
  239. public function setIgnoredAnnotationNames(array $names)
  240. {
  241. $this->ignoredAnnotationNames = $names;
  242. }
  243. /**
  244. * Sets the annotation namespaces that are ignored during the parsing process.
  245. *
  246. * @param bool[] $ignoredAnnotationNamespaces indexed by annotation namespace name
  247. *
  248. * @return void
  249. */
  250. public function setIgnoredAnnotationNamespaces($ignoredAnnotationNamespaces)
  251. {
  252. $this->ignoredAnnotationNamespaces = $ignoredAnnotationNamespaces;
  253. }
  254. /**
  255. * Sets ignore on not-imported annotations.
  256. *
  257. * @param boolean $bool
  258. *
  259. * @return void
  260. */
  261. public function setIgnoreNotImportedAnnotations($bool)
  262. {
  263. $this->ignoreNotImportedAnnotations = (boolean) $bool;
  264. }
  265. /**
  266. * Sets the default namespaces.
  267. *
  268. * @param string $namespace
  269. *
  270. * @return void
  271. *
  272. * @throws \RuntimeException
  273. */
  274. public function addNamespace($namespace)
  275. {
  276. if ($this->imports) {
  277. throw new \RuntimeException('You must either use addNamespace(), or setImports(), but not both.');
  278. }
  279. $this->namespaces[] = $namespace;
  280. }
  281. /**
  282. * Sets the imports.
  283. *
  284. * @param array $imports
  285. *
  286. * @return void
  287. *
  288. * @throws \RuntimeException
  289. */
  290. public function setImports(array $imports)
  291. {
  292. if ($this->namespaces) {
  293. throw new \RuntimeException('You must either use addNamespace(), or setImports(), but not both.');
  294. }
  295. $this->imports = $imports;
  296. }
  297. /**
  298. * Sets current target context as bitmask.
  299. *
  300. * @param integer $target
  301. *
  302. * @return void
  303. */
  304. public function setTarget($target)
  305. {
  306. $this->target = $target;
  307. }
  308. /**
  309. * Parses the given docblock string for annotations.
  310. *
  311. * @param string $input The docblock string to parse.
  312. * @param string $context The parsing context.
  313. *
  314. * @return array Array of annotations. If no annotations are found, an empty array is returned.
  315. */
  316. public function parse($input, $context = '')
  317. {
  318. $pos = $this->findInitialTokenPosition($input);
  319. if ($pos === null) {
  320. return array();
  321. }
  322. $this->context = $context;
  323. $this->lexer->setInput(trim(substr($input, $pos), '* /'));
  324. $this->lexer->moveNext();
  325. return $this->Annotations();
  326. }
  327. /**
  328. * Finds the first valid annotation
  329. *
  330. * @param string $input The docblock string to parse
  331. *
  332. * @return int|null
  333. */
  334. private function findInitialTokenPosition($input)
  335. {
  336. $pos = 0;
  337. // search for first valid annotation
  338. while (($pos = strpos($input, '@', $pos)) !== false) {
  339. $preceding = substr($input, $pos - 1, 1);
  340. // if the @ is preceded by a space, a tab or * it is valid
  341. if ($pos === 0 || $preceding === ' ' || $preceding === '*' || $preceding === "\t") {
  342. return $pos;
  343. }
  344. $pos++;
  345. }
  346. return null;
  347. }
  348. /**
  349. * Attempts to match the given token with the current lookahead token.
  350. * If they match, updates the lookahead token; otherwise raises a syntax error.
  351. *
  352. * @param integer $token Type of token.
  353. *
  354. * @return boolean True if tokens match; false otherwise.
  355. */
  356. private function match($token)
  357. {
  358. if ( ! $this->lexer->isNextToken($token) ) {
  359. $this->syntaxError($this->lexer->getLiteral($token));
  360. }
  361. return $this->lexer->moveNext();
  362. }
  363. /**
  364. * Attempts to match the current lookahead token with any of the given tokens.
  365. *
  366. * If any of them matches, this method updates the lookahead token; otherwise
  367. * a syntax error is raised.
  368. *
  369. * @param array $tokens
  370. *
  371. * @return boolean
  372. */
  373. private function matchAny(array $tokens)
  374. {
  375. if ( ! $this->lexer->isNextTokenAny($tokens)) {
  376. $this->syntaxError(implode(' or ', array_map(array($this->lexer, 'getLiteral'), $tokens)));
  377. }
  378. return $this->lexer->moveNext();
  379. }
  380. /**
  381. * Generates a new syntax error.
  382. *
  383. * @param string $expected Expected string.
  384. * @param array|null $token Optional token.
  385. *
  386. * @return void
  387. *
  388. * @throws AnnotationException
  389. */
  390. private function syntaxError($expected, $token = null)
  391. {
  392. if ($token === null) {
  393. $token = $this->lexer->lookahead;
  394. }
  395. $message = sprintf('Expected %s, got ', $expected);
  396. $message .= ($this->lexer->lookahead === null)
  397. ? 'end of string'
  398. : sprintf("'%s' at position %s", $token['value'], $token['position']);
  399. if (strlen($this->context)) {
  400. $message .= ' in ' . $this->context;
  401. }
  402. $message .= '.';
  403. throw AnnotationException::syntaxError($message);
  404. }
  405. /**
  406. * Attempts to check if a class exists or not. This never goes through the PHP autoloading mechanism
  407. * but uses the {@link AnnotationRegistry} to load classes.
  408. *
  409. * @param string $fqcn
  410. *
  411. * @return boolean
  412. */
  413. private function classExists($fqcn)
  414. {
  415. if (isset($this->classExists[$fqcn])) {
  416. return $this->classExists[$fqcn];
  417. }
  418. // first check if the class already exists, maybe loaded through another AnnotationReader
  419. if (class_exists($fqcn, false)) {
  420. return $this->classExists[$fqcn] = true;
  421. }
  422. // final check, does this class exist?
  423. return $this->classExists[$fqcn] = AnnotationRegistry::loadAnnotationClass($fqcn);
  424. }
  425. /**
  426. * Collects parsing metadata for a given annotation class
  427. *
  428. * @param string $name The annotation name
  429. *
  430. * @return void
  431. */
  432. private function collectAnnotationMetadata($name)
  433. {
  434. if (self::$metadataParser === null) {
  435. self::$metadataParser = new self();
  436. self::$metadataParser->setIgnoreNotImportedAnnotations(true);
  437. self::$metadataParser->setIgnoredAnnotationNames($this->ignoredAnnotationNames);
  438. self::$metadataParser->setImports(array(
  439. 'enum' => 'Doctrine\Common\Annotations\Annotation\Enum',
  440. 'target' => 'Doctrine\Common\Annotations\Annotation\Target',
  441. 'attribute' => 'Doctrine\Common\Annotations\Annotation\Attribute',
  442. 'attributes' => 'Doctrine\Common\Annotations\Annotation\Attributes'
  443. ));
  444. AnnotationRegistry::registerFile(__DIR__ . '/Annotation/Enum.php');
  445. AnnotationRegistry::registerFile(__DIR__ . '/Annotation/Target.php');
  446. AnnotationRegistry::registerFile(__DIR__ . '/Annotation/Attribute.php');
  447. AnnotationRegistry::registerFile(__DIR__ . '/Annotation/Attributes.php');
  448. }
  449. $class = new \ReflectionClass($name);
  450. $docComment = $class->getDocComment();
  451. // Sets default values for annotation metadata
  452. $metadata = array(
  453. 'default_property' => null,
  454. 'has_constructor' => (null !== $constructor = $class->getConstructor()) && $constructor->getNumberOfParameters() > 0,
  455. 'properties' => array(),
  456. 'property_types' => array(),
  457. 'attribute_types' => array(),
  458. 'targets_literal' => null,
  459. 'targets' => Target::TARGET_ALL,
  460. 'is_annotation' => false !== strpos($docComment, '@Annotation'),
  461. );
  462. // verify that the class is really meant to be an annotation
  463. if ($metadata['is_annotation']) {
  464. self::$metadataParser->setTarget(Target::TARGET_CLASS);
  465. foreach (self::$metadataParser->parse($docComment, 'class @' . $name) as $annotation) {
  466. if ($annotation instanceof Target) {
  467. $metadata['targets'] = $annotation->targets;
  468. $metadata['targets_literal'] = $annotation->literal;
  469. continue;
  470. }
  471. if ($annotation instanceof Attributes) {
  472. foreach ($annotation->value as $attribute) {
  473. $this->collectAttributeTypeMetadata($metadata, $attribute);
  474. }
  475. }
  476. }
  477. // if not has a constructor will inject values into public properties
  478. if (false === $metadata['has_constructor']) {
  479. // collect all public properties
  480. foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
  481. $metadata['properties'][$property->name] = $property->name;
  482. if (false === ($propertyComment = $property->getDocComment())) {
  483. continue;
  484. }
  485. $attribute = new Attribute();
  486. $attribute->required = (false !== strpos($propertyComment, '@Required'));
  487. $attribute->name = $property->name;
  488. $attribute->type = (false !== strpos($propertyComment, '@var') && preg_match('/@var\s+([^\s]+)/',$propertyComment, $matches))
  489. ? $matches[1]
  490. : 'mixed';
  491. $this->collectAttributeTypeMetadata($metadata, $attribute);
  492. // checks if the property has @Enum
  493. if (false !== strpos($propertyComment, '@Enum')) {
  494. $context = 'property ' . $class->name . "::\$" . $property->name;
  495. self::$metadataParser->setTarget(Target::TARGET_PROPERTY);
  496. foreach (self::$metadataParser->parse($propertyComment, $context) as $annotation) {
  497. if ( ! $annotation instanceof Enum) {
  498. continue;
  499. }
  500. $metadata['enum'][$property->name]['value'] = $annotation->value;
  501. $metadata['enum'][$property->name]['literal'] = ( ! empty($annotation->literal))
  502. ? $annotation->literal
  503. : $annotation->value;
  504. }
  505. }
  506. }
  507. // choose the first property as default property
  508. $metadata['default_property'] = reset($metadata['properties']);
  509. }
  510. }
  511. self::$annotationMetadata[$name] = $metadata;
  512. }
  513. /**
  514. * Collects parsing metadata for a given attribute.
  515. *
  516. * @param array $metadata
  517. * @param Attribute $attribute
  518. *
  519. * @return void
  520. */
  521. private function collectAttributeTypeMetadata(&$metadata, Attribute $attribute)
  522. {
  523. // handle internal type declaration
  524. $type = isset(self::$typeMap[$attribute->type])
  525. ? self::$typeMap[$attribute->type]
  526. : $attribute->type;
  527. // handle the case if the property type is mixed
  528. if ('mixed' === $type) {
  529. return;
  530. }
  531. // Evaluate type
  532. switch (true) {
  533. // Checks if the property has array<type>
  534. case (false !== $pos = strpos($type, '<')):
  535. $arrayType = substr($type, $pos + 1, -1);
  536. $type = 'array';
  537. if (isset(self::$typeMap[$arrayType])) {
  538. $arrayType = self::$typeMap[$arrayType];
  539. }
  540. $metadata['attribute_types'][$attribute->name]['array_type'] = $arrayType;
  541. break;
  542. // Checks if the property has type[]
  543. case (false !== $pos = strrpos($type, '[')):
  544. $arrayType = substr($type, 0, $pos);
  545. $type = 'array';
  546. if (isset(self::$typeMap[$arrayType])) {
  547. $arrayType = self::$typeMap[$arrayType];
  548. }
  549. $metadata['attribute_types'][$attribute->name]['array_type'] = $arrayType;
  550. break;
  551. }
  552. $metadata['attribute_types'][$attribute->name]['type'] = $type;
  553. $metadata['attribute_types'][$attribute->name]['value'] = $attribute->type;
  554. $metadata['attribute_types'][$attribute->name]['required'] = $attribute->required;
  555. }
  556. /**
  557. * Annotations ::= Annotation {[ "*" ]* [Annotation]}*
  558. *
  559. * @return array
  560. */
  561. private function Annotations()
  562. {
  563. $annotations = array();
  564. while (null !== $this->lexer->lookahead) {
  565. if (DocLexer::T_AT !== $this->lexer->lookahead['type']) {
  566. $this->lexer->moveNext();
  567. continue;
  568. }
  569. // make sure the @ is preceded by non-catchable pattern
  570. if (null !== $this->lexer->token && $this->lexer->lookahead['position'] === $this->lexer->token['position'] + strlen($this->lexer->token['value'])) {
  571. $this->lexer->moveNext();
  572. continue;
  573. }
  574. // make sure the @ is followed by either a namespace separator, or
  575. // an identifier token
  576. if ((null === $peek = $this->lexer->glimpse())
  577. || (DocLexer::T_NAMESPACE_SEPARATOR !== $peek['type'] && !in_array($peek['type'], self::$classIdentifiers, true))
  578. || $peek['position'] !== $this->lexer->lookahead['position'] + 1) {
  579. $this->lexer->moveNext();
  580. continue;
  581. }
  582. $this->isNestedAnnotation = false;
  583. if (false !== $annot = $this->Annotation()) {
  584. $annotations[] = $annot;
  585. }
  586. }
  587. return $annotations;
  588. }
  589. /**
  590. * Annotation ::= "@" AnnotationName MethodCall
  591. * AnnotationName ::= QualifiedName | SimpleName
  592. * QualifiedName ::= NameSpacePart "\" {NameSpacePart "\"}* SimpleName
  593. * NameSpacePart ::= identifier | null | false | true
  594. * SimpleName ::= identifier | null | false | true
  595. *
  596. * @return mixed False if it is not a valid annotation.
  597. *
  598. * @throws AnnotationException
  599. */
  600. private function Annotation()
  601. {
  602. $this->match(DocLexer::T_AT);
  603. // check if we have an annotation
  604. $name = $this->Identifier();
  605. // only process names which are not fully qualified, yet
  606. // fully qualified names must start with a \
  607. $originalName = $name;
  608. if ('\\' !== $name[0]) {
  609. $pos = strpos($name, '\\');
  610. $alias = (false === $pos)? $name : substr($name, 0, $pos);
  611. $found = false;
  612. $loweredAlias = strtolower($alias);
  613. if ($this->namespaces) {
  614. foreach ($this->namespaces as $namespace) {
  615. if ($this->classExists($namespace.'\\'.$name)) {
  616. $name = $namespace.'\\'.$name;
  617. $found = true;
  618. break;
  619. }
  620. }
  621. } elseif (isset($this->imports[$loweredAlias])) {
  622. $found = true;
  623. $name = (false !== $pos)
  624. ? $this->imports[$loweredAlias] . substr($name, $pos)
  625. : $this->imports[$loweredAlias];
  626. } elseif ( ! isset($this->ignoredAnnotationNames[$name])
  627. && isset($this->imports['__NAMESPACE__'])
  628. && $this->classExists($this->imports['__NAMESPACE__'] . '\\' . $name)
  629. ) {
  630. $name = $this->imports['__NAMESPACE__'].'\\'.$name;
  631. $found = true;
  632. } elseif (! isset($this->ignoredAnnotationNames[$name]) && $this->classExists($name)) {
  633. $found = true;
  634. }
  635. if ( ! $found) {
  636. if ($this->isIgnoredAnnotation($name)) {
  637. return false;
  638. }
  639. throw AnnotationException::semanticalError(sprintf('The annotation "@%s" in %s was never imported. Did you maybe forget to add a "use" statement for this annotation?', $name, $this->context));
  640. }
  641. }
  642. $name = ltrim($name,'\\');
  643. if ( ! $this->classExists($name)) {
  644. throw AnnotationException::semanticalError(sprintf('The annotation "@%s" in %s does not exist, or could not be auto-loaded.', $name, $this->context));
  645. }
  646. // at this point, $name contains the fully qualified class name of the
  647. // annotation, and it is also guaranteed that this class exists, and
  648. // that it is loaded
  649. // collects the metadata annotation only if there is not yet
  650. if ( ! isset(self::$annotationMetadata[$name])) {
  651. $this->collectAnnotationMetadata($name);
  652. }
  653. // verify that the class is really meant to be an annotation and not just any ordinary class
  654. if (self::$annotationMetadata[$name]['is_annotation'] === false) {
  655. if ($this->ignoreNotImportedAnnotations || isset($this->ignoredAnnotationNames[$originalName])) {
  656. return false;
  657. }
  658. throw AnnotationException::semanticalError(sprintf('The class "%s" is not annotated with @Annotation. Are you sure this class can be used as annotation? If so, then you need to add @Annotation to the _class_ doc comment of "%s". If it is indeed no annotation, then you need to add @IgnoreAnnotation("%s") to the _class_ doc comment of %s.', $name, $name, $originalName, $this->context));
  659. }
  660. //if target is nested annotation
  661. $target = $this->isNestedAnnotation ? Target::TARGET_ANNOTATION : $this->target;
  662. // Next will be nested
  663. $this->isNestedAnnotation = true;
  664. //if annotation does not support current target
  665. if (0 === (self::$annotationMetadata[$name]['targets'] & $target) && $target) {
  666. throw AnnotationException::semanticalError(
  667. sprintf('Annotation @%s is not allowed to be declared on %s. You may only use this annotation on these code elements: %s.',
  668. $originalName, $this->context, self::$annotationMetadata[$name]['targets_literal'])
  669. );
  670. }
  671. $values = $this->MethodCall();
  672. if (isset(self::$annotationMetadata[$name]['enum'])) {
  673. // checks all declared attributes
  674. foreach (self::$annotationMetadata[$name]['enum'] as $property => $enum) {
  675. // checks if the attribute is a valid enumerator
  676. if (isset($values[$property]) && ! in_array($values[$property], $enum['value'])) {
  677. throw AnnotationException::enumeratorError($property, $name, $this->context, $enum['literal'], $values[$property]);
  678. }
  679. }
  680. }
  681. // checks all declared attributes
  682. foreach (self::$annotationMetadata[$name]['attribute_types'] as $property => $type) {
  683. if ($property === self::$annotationMetadata[$name]['default_property']
  684. && !isset($values[$property]) && isset($values['value'])) {
  685. $property = 'value';
  686. }
  687. // handle a not given attribute or null value
  688. if (!isset($values[$property])) {
  689. if ($type['required']) {
  690. throw AnnotationException::requiredError($property, $originalName, $this->context, 'a(n) '.$type['value']);
  691. }
  692. continue;
  693. }
  694. if ($type['type'] === 'array') {
  695. // handle the case of a single value
  696. if ( ! is_array($values[$property])) {
  697. $values[$property] = array($values[$property]);
  698. }
  699. // checks if the attribute has array type declaration, such as "array<string>"
  700. if (isset($type['array_type'])) {
  701. foreach ($values[$property] as $item) {
  702. if (gettype($item) !== $type['array_type'] && !$item instanceof $type['array_type']) {
  703. throw AnnotationException::attributeTypeError($property, $originalName, $this->context, 'either a(n) '.$type['array_type'].', or an array of '.$type['array_type'].'s', $item);
  704. }
  705. }
  706. }
  707. } elseif (gettype($values[$property]) !== $type['type'] && !$values[$property] instanceof $type['type']) {
  708. throw AnnotationException::attributeTypeError($property, $originalName, $this->context, 'a(n) '.$type['value'], $values[$property]);
  709. }
  710. }
  711. // check if the annotation expects values via the constructor,
  712. // or directly injected into public properties
  713. if (self::$annotationMetadata[$name]['has_constructor'] === true) {
  714. return new $name($values);
  715. }
  716. $instance = new $name();
  717. foreach ($values as $property => $value) {
  718. if (!isset(self::$annotationMetadata[$name]['properties'][$property])) {
  719. if ('value' !== $property) {
  720. throw AnnotationException::creationError(sprintf('The annotation @%s declared on %s does not have a property named "%s". Available properties: %s', $originalName, $this->context, $property, implode(', ', self::$annotationMetadata[$name]['properties'])));
  721. }
  722. // handle the case if the property has no annotations
  723. if ( ! $property = self::$annotationMetadata[$name]['default_property']) {
  724. throw AnnotationException::creationError(sprintf('The annotation @%s declared on %s does not accept any values, but got %s.', $originalName, $this->context, json_encode($values)));
  725. }
  726. }
  727. $instance->{$property} = $value;
  728. }
  729. return $instance;
  730. }
  731. /**
  732. * MethodCall ::= ["(" [Values] ")"]
  733. *
  734. * @return array
  735. */
  736. private function MethodCall()
  737. {
  738. $values = array();
  739. if ( ! $this->lexer->isNextToken(DocLexer::T_OPEN_PARENTHESIS)) {
  740. return $values;
  741. }
  742. $this->match(DocLexer::T_OPEN_PARENTHESIS);
  743. if ( ! $this->lexer->isNextToken(DocLexer::T_CLOSE_PARENTHESIS)) {
  744. $values = $this->Values();
  745. }
  746. $this->match(DocLexer::T_CLOSE_PARENTHESIS);
  747. return $values;
  748. }
  749. /**
  750. * Values ::= Array | Value {"," Value}* [","]
  751. *
  752. * @return array
  753. */
  754. private function Values()
  755. {
  756. $values = array($this->Value());
  757. while ($this->lexer->isNextToken(DocLexer::T_COMMA)) {
  758. $this->match(DocLexer::T_COMMA);
  759. if ($this->lexer->isNextToken(DocLexer::T_CLOSE_PARENTHESIS)) {
  760. break;
  761. }
  762. $token = $this->lexer->lookahead;
  763. $value = $this->Value();
  764. if ( ! is_object($value) && ! is_array($value)) {
  765. $this->syntaxError('Value', $token);
  766. }
  767. $values[] = $value;
  768. }
  769. foreach ($values as $k => $value) {
  770. if (is_object($value) && $value instanceof \stdClass) {
  771. $values[$value->name] = $value->value;
  772. } else if ( ! isset($values['value'])){
  773. $values['value'] = $value;
  774. } else {
  775. if ( ! is_array($values['value'])) {
  776. $values['value'] = array($values['value']);
  777. }
  778. $values['value'][] = $value;
  779. }
  780. unset($values[$k]);
  781. }
  782. return $values;
  783. }
  784. /**
  785. * Constant ::= integer | string | float | boolean
  786. *
  787. * @return mixed
  788. *
  789. * @throws AnnotationException
  790. */
  791. private function Constant()
  792. {
  793. $identifier = $this->Identifier();
  794. if ( ! defined($identifier) && false !== strpos($identifier, '::') && '\\' !== $identifier[0]) {
  795. list($className, $const) = explode('::', $identifier);
  796. $pos = strpos($className, '\\');
  797. $alias = (false === $pos) ? $className : substr($className, 0, $pos);
  798. $found = false;
  799. $loweredAlias = strtolower($alias);
  800. switch (true) {
  801. case !empty ($this->namespaces):
  802. foreach ($this->namespaces as $ns) {
  803. if (class_exists($ns.'\\'.$className) || interface_exists($ns.'\\'.$className)) {
  804. $className = $ns.'\\'.$className;
  805. $found = true;
  806. break;
  807. }
  808. }
  809. break;
  810. case isset($this->imports[$loweredAlias]):
  811. $found = true;
  812. $className = (false !== $pos)
  813. ? $this->imports[$loweredAlias] . substr($className, $pos)
  814. : $this->imports[$loweredAlias];
  815. break;
  816. default:
  817. if(isset($this->imports['__NAMESPACE__'])) {
  818. $ns = $this->imports['__NAMESPACE__'];
  819. if (class_exists($ns.'\\'.$className) || interface_exists($ns.'\\'.$className)) {
  820. $className = $ns.'\\'.$className;
  821. $found = true;
  822. }
  823. }
  824. break;
  825. }
  826. if ($found) {
  827. $identifier = $className . '::' . $const;
  828. }
  829. }
  830. // checks if identifier ends with ::class, \strlen('::class') === 7
  831. $classPos = stripos($identifier, '::class');
  832. if ($classPos === strlen($identifier) - 7) {
  833. return substr($identifier, 0, $classPos);
  834. }
  835. if (!defined($identifier)) {
  836. throw AnnotationException::semanticalErrorConstants($identifier, $this->context);
  837. }
  838. return constant($identifier);
  839. }
  840. /**
  841. * Identifier ::= string
  842. *
  843. * @return string
  844. */
  845. private function Identifier()
  846. {
  847. // check if we have an annotation
  848. if ( ! $this->lexer->isNextTokenAny(self::$classIdentifiers)) {
  849. $this->syntaxError('namespace separator or identifier');
  850. }
  851. $this->lexer->moveNext();
  852. $className = $this->lexer->token['value'];
  853. while ($this->lexer->lookahead['position'] === ($this->lexer->token['position'] + strlen($this->lexer->token['value']))
  854. && $this->lexer->isNextToken(DocLexer::T_NAMESPACE_SEPARATOR)) {
  855. $this->match(DocLexer::T_NAMESPACE_SEPARATOR);
  856. $this->matchAny(self::$classIdentifiers);
  857. $className .= '\\' . $this->lexer->token['value'];
  858. }
  859. return $className;
  860. }
  861. /**
  862. * Value ::= PlainValue | FieldAssignment
  863. *
  864. * @return mixed
  865. */
  866. private function Value()
  867. {
  868. $peek = $this->lexer->glimpse();
  869. if (DocLexer::T_EQUALS === $peek['type']) {
  870. return $this->FieldAssignment();
  871. }
  872. return $this->PlainValue();
  873. }
  874. /**
  875. * PlainValue ::= integer | string | float | boolean | Array | Annotation
  876. *
  877. * @return mixed
  878. */
  879. private function PlainValue()
  880. {
  881. if ($this->lexer->isNextToken(DocLexer::T_OPEN_CURLY_BRACES)) {
  882. return $this->Arrayx();
  883. }
  884. if ($this->lexer->isNextToken(DocLexer::T_AT)) {
  885. return $this->Annotation();
  886. }
  887. if ($this->lexer->isNextToken(DocLexer::T_IDENTIFIER)) {
  888. return $this->Constant();
  889. }
  890. switch ($this->lexer->lookahead['type']) {
  891. case DocLexer::T_STRING:
  892. $this->match(DocLexer::T_STRING);
  893. return $this->lexer->token['value'];
  894. case DocLexer::T_INTEGER:
  895. $this->match(DocLexer::T_INTEGER);
  896. return (int)$this->lexer->token['value'];
  897. case DocLexer::T_FLOAT:
  898. $this->match(DocLexer::T_FLOAT);
  899. return (float)$this->lexer->token['value'];
  900. case DocLexer::T_TRUE:
  901. $this->match(DocLexer::T_TRUE);
  902. return true;
  903. case DocLexer::T_FALSE:
  904. $this->match(DocLexer::T_FALSE);
  905. return false;
  906. case DocLexer::T_NULL:
  907. $this->match(DocLexer::T_NULL);
  908. return null;
  909. default:
  910. $this->syntaxError('PlainValue');
  911. }
  912. }
  913. /**
  914. * FieldAssignment ::= FieldName "=" PlainValue
  915. * FieldName ::= identifier
  916. *
  917. * @return \stdClass
  918. */
  919. private function FieldAssignment()
  920. {
  921. $this->match(DocLexer::T_IDENTIFIER);
  922. $fieldName = $this->lexer->token['value'];
  923. $this->match(DocLexer::T_EQUALS);
  924. $item = new \stdClass();
  925. $item->name = $fieldName;
  926. $item->value = $this->PlainValue();
  927. return $item;
  928. }
  929. /**
  930. * Array ::= "{" ArrayEntry {"," ArrayEntry}* [","] "}"
  931. *
  932. * @return array
  933. */
  934. private function Arrayx()
  935. {
  936. $array = $values = array();
  937. $this->match(DocLexer::T_OPEN_CURLY_BRACES);
  938. // If the array is empty, stop parsing and return.
  939. if ($this->lexer->isNextToken(DocLexer::T_CLOSE_CURLY_BRACES)) {
  940. $this->match(DocLexer::T_CLOSE_CURLY_BRACES);
  941. return $array;
  942. }
  943. $values[] = $this->ArrayEntry();
  944. while ($this->lexer->isNextToken(DocLexer::T_COMMA)) {
  945. $this->match(DocLexer::T_COMMA);
  946. // optional trailing comma
  947. if ($this->lexer->isNextToken(DocLexer::T_CLOSE_CURLY_BRACES)) {
  948. break;
  949. }
  950. $values[] = $this->ArrayEntry();
  951. }
  952. $this->match(DocLexer::T_CLOSE_CURLY_BRACES);
  953. foreach ($values as $value) {
  954. list ($key, $val) = $value;
  955. if ($key !== null) {
  956. $array[$key] = $val;
  957. } else {
  958. $array[] = $val;
  959. }
  960. }
  961. return $array;
  962. }
  963. /**
  964. * ArrayEntry ::= Value | KeyValuePair
  965. * KeyValuePair ::= Key ("=" | ":") PlainValue | Constant
  966. * Key ::= string | integer | Constant
  967. *
  968. * @return array
  969. */
  970. private function ArrayEntry()
  971. {
  972. $peek = $this->lexer->glimpse();
  973. if (DocLexer::T_EQUALS === $peek['type']
  974. || DocLexer::T_COLON === $peek['type']) {
  975. if ($this->lexer->isNextToken(DocLexer::T_IDENTIFIER)) {
  976. $key = $this->Constant();
  977. } else {
  978. $this->matchAny(array(DocLexer::T_INTEGER, DocLexer::T_STRING));
  979. $key = $this->lexer->token['value'];
  980. }
  981. $this->matchAny(array(DocLexer::T_EQUALS, DocLexer::T_COLON));
  982. return array($key, $this->PlainValue());
  983. }
  984. return array(null, $this->Value());
  985. }
  986. /**
  987. * Checks whether the given $name matches any ignored annotation name or namespace
  988. *
  989. * @param string $name
  990. *
  991. * @return bool
  992. */
  993. private function isIgnoredAnnotation($name)
  994. {
  995. if ($this->ignoreNotImportedAnnotations || isset($this->ignoredAnnotationNames[$name])) {
  996. return true;
  997. }
  998. foreach (array_keys($this->ignoredAnnotationNamespaces) as $ignoredAnnotationNamespace) {
  999. $ignoredAnnotationNamespace = rtrim($ignoredAnnotationNamespace, '\\') . '\\';
  1000. if (0 === stripos(rtrim($name, '\\') . '\\', $ignoredAnnotationNamespace)) {
  1001. return true;
  1002. }
  1003. }
  1004. return false;
  1005. }
  1006. }