DocParser.php 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506
  1. <?php
  2. namespace Doctrine\Common\Annotations;
  3. use Doctrine\Common\Annotations\Annotation\Attribute;
  4. use Doctrine\Common\Annotations\Annotation\Attributes;
  5. use Doctrine\Common\Annotations\Annotation\Enum;
  6. use Doctrine\Common\Annotations\Annotation\NamedArgumentConstructor;
  7. use Doctrine\Common\Annotations\Annotation\Target;
  8. use ReflectionClass;
  9. use ReflectionException;
  10. use ReflectionProperty;
  11. use RuntimeException;
  12. use stdClass;
  13. use Throwable;
  14. use function array_keys;
  15. use function array_map;
  16. use function array_pop;
  17. use function array_values;
  18. use function class_exists;
  19. use function constant;
  20. use function count;
  21. use function defined;
  22. use function explode;
  23. use function gettype;
  24. use function implode;
  25. use function in_array;
  26. use function interface_exists;
  27. use function is_array;
  28. use function is_object;
  29. use function json_encode;
  30. use function ltrim;
  31. use function preg_match;
  32. use function reset;
  33. use function rtrim;
  34. use function sprintf;
  35. use function stripos;
  36. use function strlen;
  37. use function strpos;
  38. use function strrpos;
  39. use function strtolower;
  40. use function substr;
  41. use function trim;
  42. use const PHP_VERSION_ID;
  43. /**
  44. * A parser for docblock annotations.
  45. *
  46. * It is strongly discouraged to change the default annotation parsing process.
  47. */
  48. final class DocParser
  49. {
  50. /**
  51. * An array of all valid tokens for a class name.
  52. *
  53. * @phpstan-var list<int>
  54. */
  55. private static $classIdentifiers = [
  56. DocLexer::T_IDENTIFIER,
  57. DocLexer::T_TRUE,
  58. DocLexer::T_FALSE,
  59. DocLexer::T_NULL,
  60. ];
  61. /**
  62. * The lexer.
  63. *
  64. * @var DocLexer
  65. */
  66. private $lexer;
  67. /**
  68. * Current target context.
  69. *
  70. * @var int
  71. */
  72. private $target;
  73. /**
  74. * Doc parser used to collect annotation target.
  75. *
  76. * @var DocParser
  77. */
  78. private static $metadataParser;
  79. /**
  80. * Flag to control if the current annotation is nested or not.
  81. *
  82. * @var bool
  83. */
  84. private $isNestedAnnotation = false;
  85. /**
  86. * Hashmap containing all use-statements that are to be used when parsing
  87. * the given doc block.
  88. *
  89. * @var array<string, class-string>
  90. */
  91. private $imports = [];
  92. /**
  93. * This hashmap is used internally to cache results of class_exists()
  94. * look-ups.
  95. *
  96. * @var array<class-string, bool>
  97. */
  98. private $classExists = [];
  99. /**
  100. * Whether annotations that have not been imported should be ignored.
  101. *
  102. * @var bool
  103. */
  104. private $ignoreNotImportedAnnotations = false;
  105. /**
  106. * An array of default namespaces if operating in simple mode.
  107. *
  108. * @var string[]
  109. */
  110. private $namespaces = [];
  111. /**
  112. * A list with annotations that are not causing exceptions when not resolved to an annotation class.
  113. *
  114. * The names must be the raw names as used in the class, not the fully qualified
  115. *
  116. * @var bool[] indexed by annotation name
  117. */
  118. private $ignoredAnnotationNames = [];
  119. /**
  120. * A list with annotations in namespaced format
  121. * that are not causing exceptions when not resolved to an annotation class.
  122. *
  123. * @var bool[] indexed by namespace name
  124. */
  125. private $ignoredAnnotationNamespaces = [];
  126. /** @var string */
  127. private $context = '';
  128. /**
  129. * Hash-map for caching annotation metadata.
  130. *
  131. * @var array<class-string, mixed[]>
  132. */
  133. private static $annotationMetadata = [
  134. Annotation\Target::class => [
  135. 'is_annotation' => true,
  136. 'has_constructor' => true,
  137. 'has_named_argument_constructor' => false,
  138. 'properties' => [],
  139. 'targets_literal' => 'ANNOTATION_CLASS',
  140. 'targets' => Target::TARGET_CLASS,
  141. 'default_property' => 'value',
  142. 'attribute_types' => [
  143. 'value' => [
  144. 'required' => false,
  145. 'type' => 'array',
  146. 'array_type' => 'string',
  147. 'value' => 'array<string>',
  148. ],
  149. ],
  150. ],
  151. Annotation\Attribute::class => [
  152. 'is_annotation' => true,
  153. 'has_constructor' => false,
  154. 'has_named_argument_constructor' => false,
  155. 'targets_literal' => 'ANNOTATION_ANNOTATION',
  156. 'targets' => Target::TARGET_ANNOTATION,
  157. 'default_property' => 'name',
  158. 'properties' => [
  159. 'name' => 'name',
  160. 'type' => 'type',
  161. 'required' => 'required',
  162. ],
  163. 'attribute_types' => [
  164. 'value' => [
  165. 'required' => true,
  166. 'type' => 'string',
  167. 'value' => 'string',
  168. ],
  169. 'type' => [
  170. 'required' => true,
  171. 'type' => 'string',
  172. 'value' => 'string',
  173. ],
  174. 'required' => [
  175. 'required' => false,
  176. 'type' => 'boolean',
  177. 'value' => 'boolean',
  178. ],
  179. ],
  180. ],
  181. Annotation\Attributes::class => [
  182. 'is_annotation' => true,
  183. 'has_constructor' => false,
  184. 'has_named_argument_constructor' => false,
  185. 'targets_literal' => 'ANNOTATION_CLASS',
  186. 'targets' => Target::TARGET_CLASS,
  187. 'default_property' => 'value',
  188. 'properties' => ['value' => 'value'],
  189. 'attribute_types' => [
  190. 'value' => [
  191. 'type' => 'array',
  192. 'required' => true,
  193. 'array_type' => Annotation\Attribute::class,
  194. 'value' => 'array<' . Annotation\Attribute::class . '>',
  195. ],
  196. ],
  197. ],
  198. Annotation\Enum::class => [
  199. 'is_annotation' => true,
  200. 'has_constructor' => true,
  201. 'has_named_argument_constructor' => false,
  202. 'targets_literal' => 'ANNOTATION_PROPERTY',
  203. 'targets' => Target::TARGET_PROPERTY,
  204. 'default_property' => 'value',
  205. 'properties' => ['value' => 'value'],
  206. 'attribute_types' => [
  207. 'value' => [
  208. 'type' => 'array',
  209. 'required' => true,
  210. ],
  211. 'literal' => [
  212. 'type' => 'array',
  213. 'required' => false,
  214. ],
  215. ],
  216. ],
  217. Annotation\NamedArgumentConstructor::class => [
  218. 'is_annotation' => true,
  219. 'has_constructor' => false,
  220. 'has_named_argument_constructor' => false,
  221. 'targets_literal' => 'ANNOTATION_CLASS',
  222. 'targets' => Target::TARGET_CLASS,
  223. 'default_property' => null,
  224. 'properties' => [],
  225. 'attribute_types' => [],
  226. ],
  227. ];
  228. /**
  229. * Hash-map for handle types declaration.
  230. *
  231. * @var array<string, string>
  232. */
  233. private static $typeMap = [
  234. 'float' => 'double',
  235. 'bool' => 'boolean',
  236. // allow uppercase Boolean in honor of George Boole
  237. 'Boolean' => 'boolean',
  238. 'int' => 'integer',
  239. ];
  240. /**
  241. * Constructs a new DocParser.
  242. */
  243. public function __construct()
  244. {
  245. $this->lexer = new DocLexer();
  246. }
  247. /**
  248. * Sets the annotation names that are ignored during the parsing process.
  249. *
  250. * The names are supposed to be the raw names as used in the class, not the
  251. * fully qualified class names.
  252. *
  253. * @param bool[] $names indexed by annotation name
  254. *
  255. * @return void
  256. */
  257. public function setIgnoredAnnotationNames(array $names)
  258. {
  259. $this->ignoredAnnotationNames = $names;
  260. }
  261. /**
  262. * Sets the annotation namespaces that are ignored during the parsing process.
  263. *
  264. * @param bool[] $ignoredAnnotationNamespaces indexed by annotation namespace name
  265. *
  266. * @return void
  267. */
  268. public function setIgnoredAnnotationNamespaces($ignoredAnnotationNamespaces)
  269. {
  270. $this->ignoredAnnotationNamespaces = $ignoredAnnotationNamespaces;
  271. }
  272. /**
  273. * Sets ignore on not-imported annotations.
  274. *
  275. * @param bool $bool
  276. *
  277. * @return void
  278. */
  279. public function setIgnoreNotImportedAnnotations($bool)
  280. {
  281. $this->ignoreNotImportedAnnotations = (bool) $bool;
  282. }
  283. /**
  284. * Sets the default namespaces.
  285. *
  286. * @param string $namespace
  287. *
  288. * @return void
  289. *
  290. * @throws RuntimeException
  291. */
  292. public function addNamespace($namespace)
  293. {
  294. if ($this->imports) {
  295. throw new RuntimeException('You must either use addNamespace(), or setImports(), but not both.');
  296. }
  297. $this->namespaces[] = $namespace;
  298. }
  299. /**
  300. * Sets the imports.
  301. *
  302. * @param array<string, class-string> $imports
  303. *
  304. * @return void
  305. *
  306. * @throws RuntimeException
  307. */
  308. public function setImports(array $imports)
  309. {
  310. if ($this->namespaces) {
  311. throw new RuntimeException('You must either use addNamespace(), or setImports(), but not both.');
  312. }
  313. $this->imports = $imports;
  314. }
  315. /**
  316. * Sets current target context as bitmask.
  317. *
  318. * @param int $target
  319. *
  320. * @return void
  321. */
  322. public function setTarget($target)
  323. {
  324. $this->target = $target;
  325. }
  326. /**
  327. * Parses the given docblock string for annotations.
  328. *
  329. * @param string $input The docblock string to parse.
  330. * @param string $context The parsing context.
  331. *
  332. * @phpstan-return list<object> Array of annotations. If no annotations are found, an empty array is returned.
  333. *
  334. * @throws AnnotationException
  335. * @throws ReflectionException
  336. */
  337. public function parse($input, $context = '')
  338. {
  339. $pos = $this->findInitialTokenPosition($input);
  340. if ($pos === null) {
  341. return [];
  342. }
  343. $this->context = $context;
  344. $this->lexer->setInput(trim(substr($input, $pos), '* /'));
  345. $this->lexer->moveNext();
  346. return $this->Annotations();
  347. }
  348. /**
  349. * Finds the first valid annotation
  350. *
  351. * @param string $input The docblock string to parse
  352. */
  353. private function findInitialTokenPosition($input): ?int
  354. {
  355. $pos = 0;
  356. // search for first valid annotation
  357. while (($pos = strpos($input, '@', $pos)) !== false) {
  358. $preceding = substr($input, $pos - 1, 1);
  359. // if the @ is preceded by a space, a tab or * it is valid
  360. if ($pos === 0 || $preceding === ' ' || $preceding === '*' || $preceding === "\t") {
  361. return $pos;
  362. }
  363. $pos++;
  364. }
  365. return null;
  366. }
  367. /**
  368. * Attempts to match the given token with the current lookahead token.
  369. * If they match, updates the lookahead token; otherwise raises a syntax error.
  370. *
  371. * @param int $token Type of token.
  372. *
  373. * @return bool True if tokens match; false otherwise.
  374. *
  375. * @throws AnnotationException
  376. */
  377. private function match(int $token): bool
  378. {
  379. if (! $this->lexer->isNextToken($token)) {
  380. throw $this->syntaxError($this->lexer->getLiteral($token));
  381. }
  382. return $this->lexer->moveNext();
  383. }
  384. /**
  385. * Attempts to match the current lookahead token with any of the given tokens.
  386. *
  387. * If any of them matches, this method updates the lookahead token; otherwise
  388. * a syntax error is raised.
  389. *
  390. * @phpstan-param list<mixed[]> $tokens
  391. *
  392. * @throws AnnotationException
  393. */
  394. private function matchAny(array $tokens): bool
  395. {
  396. if (! $this->lexer->isNextTokenAny($tokens)) {
  397. throw $this->syntaxError(implode(' or ', array_map([$this->lexer, 'getLiteral'], $tokens)));
  398. }
  399. return $this->lexer->moveNext();
  400. }
  401. /**
  402. * Generates a new syntax error.
  403. *
  404. * @param string $expected Expected string.
  405. * @param mixed[]|null $token Optional token.
  406. */
  407. private function syntaxError(string $expected, ?array $token = null): AnnotationException
  408. {
  409. if ($token === null) {
  410. $token = $this->lexer->lookahead;
  411. }
  412. $message = sprintf('Expected %s, got ', $expected);
  413. $message .= $this->lexer->lookahead === null
  414. ? 'end of string'
  415. : sprintf("'%s' at position %s", $token['value'], $token['position']);
  416. if (strlen($this->context)) {
  417. $message .= ' in ' . $this->context;
  418. }
  419. $message .= '.';
  420. return AnnotationException::syntaxError($message);
  421. }
  422. /**
  423. * Attempts to check if a class exists or not. This never goes through the PHP autoloading mechanism
  424. * but uses the {@link AnnotationRegistry} to load classes.
  425. *
  426. * @param class-string $fqcn
  427. */
  428. private function classExists(string $fqcn): bool
  429. {
  430. if (isset($this->classExists[$fqcn])) {
  431. return $this->classExists[$fqcn];
  432. }
  433. // first check if the class already exists, maybe loaded through another AnnotationReader
  434. if (class_exists($fqcn, false)) {
  435. return $this->classExists[$fqcn] = true;
  436. }
  437. // final check, does this class exist?
  438. return $this->classExists[$fqcn] = AnnotationRegistry::loadAnnotationClass($fqcn);
  439. }
  440. /**
  441. * Collects parsing metadata for a given annotation class
  442. *
  443. * @param class-string $name The annotation name
  444. *
  445. * @throws AnnotationException
  446. * @throws ReflectionException
  447. */
  448. private function collectAnnotationMetadata(string $name): void
  449. {
  450. if (self::$metadataParser === null) {
  451. self::$metadataParser = new self();
  452. self::$metadataParser->setIgnoreNotImportedAnnotations(true);
  453. self::$metadataParser->setIgnoredAnnotationNames($this->ignoredAnnotationNames);
  454. self::$metadataParser->setImports([
  455. 'enum' => Enum::class,
  456. 'target' => Target::class,
  457. 'attribute' => Attribute::class,
  458. 'attributes' => Attributes::class,
  459. 'namedargumentconstructor' => NamedArgumentConstructor::class,
  460. ]);
  461. // Make sure that annotations from metadata are loaded
  462. class_exists(Enum::class);
  463. class_exists(Target::class);
  464. class_exists(Attribute::class);
  465. class_exists(Attributes::class);
  466. class_exists(NamedArgumentConstructor::class);
  467. }
  468. $class = new ReflectionClass($name);
  469. $docComment = $class->getDocComment();
  470. // Sets default values for annotation metadata
  471. $constructor = $class->getConstructor();
  472. $metadata = [
  473. 'default_property' => null,
  474. 'has_constructor' => $constructor !== null && $constructor->getNumberOfParameters() > 0,
  475. 'constructor_args' => [],
  476. 'properties' => [],
  477. 'property_types' => [],
  478. 'attribute_types' => [],
  479. 'targets_literal' => null,
  480. 'targets' => Target::TARGET_ALL,
  481. 'is_annotation' => strpos($docComment, '@Annotation') !== false,
  482. ];
  483. $metadata['has_named_argument_constructor'] = $metadata['has_constructor']
  484. && $class->implementsInterface(NamedArgumentConstructorAnnotation::class);
  485. // verify that the class is really meant to be an annotation
  486. if ($metadata['is_annotation']) {
  487. self::$metadataParser->setTarget(Target::TARGET_CLASS);
  488. foreach (self::$metadataParser->parse($docComment, 'class @' . $name) as $annotation) {
  489. if ($annotation instanceof Target) {
  490. $metadata['targets'] = $annotation->targets;
  491. $metadata['targets_literal'] = $annotation->literal;
  492. continue;
  493. }
  494. if ($annotation instanceof NamedArgumentConstructor) {
  495. $metadata['has_named_argument_constructor'] = $metadata['has_constructor'];
  496. if ($metadata['has_named_argument_constructor']) {
  497. // choose the first argument as the default property
  498. $metadata['default_property'] = $constructor->getParameters()[0]->getName();
  499. }
  500. }
  501. if (! ($annotation instanceof Attributes)) {
  502. continue;
  503. }
  504. foreach ($annotation->value as $attribute) {
  505. $this->collectAttributeTypeMetadata($metadata, $attribute);
  506. }
  507. }
  508. // if not has a constructor will inject values into public properties
  509. if ($metadata['has_constructor'] === false) {
  510. // collect all public properties
  511. foreach ($class->getProperties(ReflectionProperty::IS_PUBLIC) as $property) {
  512. $metadata['properties'][$property->name] = $property->name;
  513. $propertyComment = $property->getDocComment();
  514. if ($propertyComment === false) {
  515. continue;
  516. }
  517. $attribute = new Attribute();
  518. $attribute->required = (strpos($propertyComment, '@Required') !== false);
  519. $attribute->name = $property->name;
  520. $attribute->type = (strpos($propertyComment, '@var') !== false &&
  521. preg_match('/@var\s+([^\s]+)/', $propertyComment, $matches))
  522. ? $matches[1]
  523. : 'mixed';
  524. $this->collectAttributeTypeMetadata($metadata, $attribute);
  525. // checks if the property has @Enum
  526. if (strpos($propertyComment, '@Enum') === false) {
  527. continue;
  528. }
  529. $context = 'property ' . $class->name . '::$' . $property->name;
  530. self::$metadataParser->setTarget(Target::TARGET_PROPERTY);
  531. foreach (self::$metadataParser->parse($propertyComment, $context) as $annotation) {
  532. if (! $annotation instanceof Enum) {
  533. continue;
  534. }
  535. $metadata['enum'][$property->name]['value'] = $annotation->value;
  536. $metadata['enum'][$property->name]['literal'] = (! empty($annotation->literal))
  537. ? $annotation->literal
  538. : $annotation->value;
  539. }
  540. }
  541. // choose the first property as default property
  542. $metadata['default_property'] = reset($metadata['properties']);
  543. } elseif ($metadata['has_named_argument_constructor']) {
  544. foreach ($constructor->getParameters() as $parameter) {
  545. if ($parameter->isVariadic()) {
  546. break;
  547. }
  548. $metadata['constructor_args'][$parameter->getName()] = [
  549. 'position' => $parameter->getPosition(),
  550. 'default' => $parameter->isOptional() ? $parameter->getDefaultValue() : null,
  551. ];
  552. }
  553. }
  554. }
  555. self::$annotationMetadata[$name] = $metadata;
  556. }
  557. /**
  558. * Collects parsing metadata for a given attribute.
  559. *
  560. * @param mixed[] $metadata
  561. */
  562. private function collectAttributeTypeMetadata(array &$metadata, Attribute $attribute): void
  563. {
  564. // handle internal type declaration
  565. $type = self::$typeMap[$attribute->type] ?? $attribute->type;
  566. // handle the case if the property type is mixed
  567. if ($type === 'mixed') {
  568. return;
  569. }
  570. // Evaluate type
  571. $pos = strpos($type, '<');
  572. if ($pos !== false) {
  573. // Checks if the property has array<type>
  574. $arrayType = substr($type, $pos + 1, -1);
  575. $type = 'array';
  576. if (isset(self::$typeMap[$arrayType])) {
  577. $arrayType = self::$typeMap[$arrayType];
  578. }
  579. $metadata['attribute_types'][$attribute->name]['array_type'] = $arrayType;
  580. } else {
  581. // Checks if the property has type[]
  582. $pos = strrpos($type, '[');
  583. if ($pos !== false) {
  584. $arrayType = substr($type, 0, $pos);
  585. $type = 'array';
  586. if (isset(self::$typeMap[$arrayType])) {
  587. $arrayType = self::$typeMap[$arrayType];
  588. }
  589. $metadata['attribute_types'][$attribute->name]['array_type'] = $arrayType;
  590. }
  591. }
  592. $metadata['attribute_types'][$attribute->name]['type'] = $type;
  593. $metadata['attribute_types'][$attribute->name]['value'] = $attribute->type;
  594. $metadata['attribute_types'][$attribute->name]['required'] = $attribute->required;
  595. }
  596. /**
  597. * Annotations ::= Annotation {[ "*" ]* [Annotation]}*
  598. *
  599. * @phpstan-return list<object>
  600. *
  601. * @throws AnnotationException
  602. * @throws ReflectionException
  603. */
  604. private function Annotations(): array
  605. {
  606. $annotations = [];
  607. while ($this->lexer->lookahead !== null) {
  608. if ($this->lexer->lookahead['type'] !== DocLexer::T_AT) {
  609. $this->lexer->moveNext();
  610. continue;
  611. }
  612. // make sure the @ is preceded by non-catchable pattern
  613. if (
  614. $this->lexer->token !== null &&
  615. $this->lexer->lookahead['position'] === $this->lexer->token['position'] + strlen(
  616. $this->lexer->token['value']
  617. )
  618. ) {
  619. $this->lexer->moveNext();
  620. continue;
  621. }
  622. // make sure the @ is followed by either a namespace separator, or
  623. // an identifier token
  624. $peek = $this->lexer->glimpse();
  625. if (
  626. ($peek === null)
  627. || ($peek['type'] !== DocLexer::T_NAMESPACE_SEPARATOR && ! in_array(
  628. $peek['type'],
  629. self::$classIdentifiers,
  630. true
  631. ))
  632. || $peek['position'] !== $this->lexer->lookahead['position'] + 1
  633. ) {
  634. $this->lexer->moveNext();
  635. continue;
  636. }
  637. $this->isNestedAnnotation = false;
  638. $annot = $this->Annotation();
  639. if ($annot === false) {
  640. continue;
  641. }
  642. $annotations[] = $annot;
  643. }
  644. return $annotations;
  645. }
  646. /**
  647. * Annotation ::= "@" AnnotationName MethodCall
  648. * AnnotationName ::= QualifiedName | SimpleName
  649. * QualifiedName ::= NameSpacePart "\" {NameSpacePart "\"}* SimpleName
  650. * NameSpacePart ::= identifier | null | false | true
  651. * SimpleName ::= identifier | null | false | true
  652. *
  653. * @return object|false False if it is not a valid annotation.
  654. *
  655. * @throws AnnotationException
  656. * @throws ReflectionException
  657. */
  658. private function Annotation()
  659. {
  660. $this->match(DocLexer::T_AT);
  661. // check if we have an annotation
  662. $name = $this->Identifier();
  663. if (
  664. $this->lexer->isNextToken(DocLexer::T_MINUS)
  665. && $this->lexer->nextTokenIsAdjacent()
  666. ) {
  667. // Annotations with dashes, such as "@foo-" or "@foo-bar", are to be discarded
  668. return false;
  669. }
  670. // only process names which are not fully qualified, yet
  671. // fully qualified names must start with a \
  672. $originalName = $name;
  673. if ($name[0] !== '\\') {
  674. $pos = strpos($name, '\\');
  675. $alias = ($pos === false) ? $name : substr($name, 0, $pos);
  676. $found = false;
  677. $loweredAlias = strtolower($alias);
  678. if ($this->namespaces) {
  679. foreach ($this->namespaces as $namespace) {
  680. if ($this->classExists($namespace . '\\' . $name)) {
  681. $name = $namespace . '\\' . $name;
  682. $found = true;
  683. break;
  684. }
  685. }
  686. } elseif (isset($this->imports[$loweredAlias])) {
  687. $namespace = ltrim($this->imports[$loweredAlias], '\\');
  688. $name = ($pos !== false)
  689. ? $namespace . substr($name, $pos)
  690. : $namespace;
  691. $found = $this->classExists($name);
  692. } elseif (
  693. ! isset($this->ignoredAnnotationNames[$name])
  694. && isset($this->imports['__NAMESPACE__'])
  695. && $this->classExists($this->imports['__NAMESPACE__'] . '\\' . $name)
  696. ) {
  697. $name = $this->imports['__NAMESPACE__'] . '\\' . $name;
  698. $found = true;
  699. } elseif (! isset($this->ignoredAnnotationNames[$name]) && $this->classExists($name)) {
  700. $found = true;
  701. }
  702. if (! $found) {
  703. if ($this->isIgnoredAnnotation($name)) {
  704. return false;
  705. }
  706. throw AnnotationException::semanticalError(sprintf(
  707. <<<'EXCEPTION'
  708. The annotation "@%s" in %s was never imported. Did you maybe forget to add a "use" statement for this annotation?
  709. EXCEPTION
  710. ,
  711. $name,
  712. $this->context
  713. ));
  714. }
  715. }
  716. $name = ltrim($name, '\\');
  717. if (! $this->classExists($name)) {
  718. throw AnnotationException::semanticalError(sprintf(
  719. 'The annotation "@%s" in %s does not exist, or could not be auto-loaded.',
  720. $name,
  721. $this->context
  722. ));
  723. }
  724. // at this point, $name contains the fully qualified class name of the
  725. // annotation, and it is also guaranteed that this class exists, and
  726. // that it is loaded
  727. // collects the metadata annotation only if there is not yet
  728. if (! isset(self::$annotationMetadata[$name])) {
  729. $this->collectAnnotationMetadata($name);
  730. }
  731. // verify that the class is really meant to be an annotation and not just any ordinary class
  732. if (self::$annotationMetadata[$name]['is_annotation'] === false) {
  733. if ($this->isIgnoredAnnotation($originalName) || $this->isIgnoredAnnotation($name)) {
  734. return false;
  735. }
  736. throw AnnotationException::semanticalError(sprintf(
  737. <<<'EXCEPTION'
  738. The class "%s" is not annotated with @Annotation.
  739. Are you sure this class can be used as annotation?
  740. If so, then you need to add @Annotation to the _class_ doc comment of "%s".
  741. If it is indeed no annotation, then you need to add @IgnoreAnnotation("%s") to the _class_ doc comment of %s.
  742. EXCEPTION
  743. ,
  744. $name,
  745. $name,
  746. $originalName,
  747. $this->context
  748. ));
  749. }
  750. //if target is nested annotation
  751. $target = $this->isNestedAnnotation ? Target::TARGET_ANNOTATION : $this->target;
  752. // Next will be nested
  753. $this->isNestedAnnotation = true;
  754. //if annotation does not support current target
  755. if ((self::$annotationMetadata[$name]['targets'] & $target) === 0 && $target) {
  756. throw AnnotationException::semanticalError(
  757. sprintf(
  758. <<<'EXCEPTION'
  759. Annotation @%s is not allowed to be declared on %s. You may only use this annotation on these code elements: %s.
  760. EXCEPTION
  761. ,
  762. $originalName,
  763. $this->context,
  764. self::$annotationMetadata[$name]['targets_literal']
  765. )
  766. );
  767. }
  768. $arguments = $this->MethodCall();
  769. $values = $this->resolvePositionalValues($arguments, $name);
  770. if (isset(self::$annotationMetadata[$name]['enum'])) {
  771. // checks all declared attributes
  772. foreach (self::$annotationMetadata[$name]['enum'] as $property => $enum) {
  773. // checks if the attribute is a valid enumerator
  774. if (isset($values[$property]) && ! in_array($values[$property], $enum['value'])) {
  775. throw AnnotationException::enumeratorError(
  776. $property,
  777. $name,
  778. $this->context,
  779. $enum['literal'],
  780. $values[$property]
  781. );
  782. }
  783. }
  784. }
  785. // checks all declared attributes
  786. foreach (self::$annotationMetadata[$name]['attribute_types'] as $property => $type) {
  787. if (
  788. $property === self::$annotationMetadata[$name]['default_property']
  789. && ! isset($values[$property]) && isset($values['value'])
  790. ) {
  791. $property = 'value';
  792. }
  793. // handle a not given attribute or null value
  794. if (! isset($values[$property])) {
  795. if ($type['required']) {
  796. throw AnnotationException::requiredError(
  797. $property,
  798. $originalName,
  799. $this->context,
  800. 'a(n) ' . $type['value']
  801. );
  802. }
  803. continue;
  804. }
  805. if ($type['type'] === 'array') {
  806. // handle the case of a single value
  807. if (! is_array($values[$property])) {
  808. $values[$property] = [$values[$property]];
  809. }
  810. // checks if the attribute has array type declaration, such as "array<string>"
  811. if (isset($type['array_type'])) {
  812. foreach ($values[$property] as $item) {
  813. if (gettype($item) !== $type['array_type'] && ! $item instanceof $type['array_type']) {
  814. throw AnnotationException::attributeTypeError(
  815. $property,
  816. $originalName,
  817. $this->context,
  818. 'either a(n) ' . $type['array_type'] . ', or an array of ' . $type['array_type'] . 's',
  819. $item
  820. );
  821. }
  822. }
  823. }
  824. } elseif (gettype($values[$property]) !== $type['type'] && ! $values[$property] instanceof $type['type']) {
  825. throw AnnotationException::attributeTypeError(
  826. $property,
  827. $originalName,
  828. $this->context,
  829. 'a(n) ' . $type['value'],
  830. $values[$property]
  831. );
  832. }
  833. }
  834. if (self::$annotationMetadata[$name]['has_named_argument_constructor']) {
  835. if (PHP_VERSION_ID >= 80000) {
  836. foreach ($values as $property => $value) {
  837. if (! isset(self::$annotationMetadata[$name]['constructor_args'][$property])) {
  838. throw AnnotationException::creationError(sprintf(
  839. <<<'EXCEPTION'
  840. The annotation @%s declared on %s does not have a property named "%s"
  841. that can be set through its named arguments constructor.
  842. Available named arguments: %s
  843. EXCEPTION
  844. ,
  845. $originalName,
  846. $this->context,
  847. $property,
  848. implode(', ', array_keys(self::$annotationMetadata[$name]['constructor_args']))
  849. ));
  850. }
  851. }
  852. return $this->instantiateAnnotiation($originalName, $this->context, $name, $values);
  853. }
  854. $positionalValues = [];
  855. foreach (self::$annotationMetadata[$name]['constructor_args'] as $property => $parameter) {
  856. $positionalValues[$parameter['position']] = $parameter['default'];
  857. }
  858. foreach ($values as $property => $value) {
  859. if (! isset(self::$annotationMetadata[$name]['constructor_args'][$property])) {
  860. throw AnnotationException::creationError(sprintf(
  861. <<<'EXCEPTION'
  862. The annotation @%s declared on %s does not have a property named "%s"
  863. that can be set through its named arguments constructor.
  864. Available named arguments: %s
  865. EXCEPTION
  866. ,
  867. $originalName,
  868. $this->context,
  869. $property,
  870. implode(', ', array_keys(self::$annotationMetadata[$name]['constructor_args']))
  871. ));
  872. }
  873. $positionalValues[self::$annotationMetadata[$name]['constructor_args'][$property]['position']] = $value;
  874. }
  875. return $this->instantiateAnnotiation($originalName, $this->context, $name, $positionalValues);
  876. }
  877. // check if the annotation expects values via the constructor,
  878. // or directly injected into public properties
  879. if (self::$annotationMetadata[$name]['has_constructor'] === true) {
  880. return $this->instantiateAnnotiation($originalName, $this->context, $name, [$values]);
  881. }
  882. $instance = $this->instantiateAnnotiation($originalName, $this->context, $name, []);
  883. foreach ($values as $property => $value) {
  884. if (! isset(self::$annotationMetadata[$name]['properties'][$property])) {
  885. if ($property !== 'value') {
  886. throw AnnotationException::creationError(sprintf(
  887. <<<'EXCEPTION'
  888. The annotation @%s declared on %s does not have a property named "%s".
  889. Available properties: %s
  890. EXCEPTION
  891. ,
  892. $originalName,
  893. $this->context,
  894. $property,
  895. implode(', ', self::$annotationMetadata[$name]['properties'])
  896. ));
  897. }
  898. // handle the case if the property has no annotations
  899. $property = self::$annotationMetadata[$name]['default_property'];
  900. if (! $property) {
  901. throw AnnotationException::creationError(sprintf(
  902. 'The annotation @%s declared on %s does not accept any values, but got %s.',
  903. $originalName,
  904. $this->context,
  905. json_encode($values)
  906. ));
  907. }
  908. }
  909. $instance->{$property} = $value;
  910. }
  911. return $instance;
  912. }
  913. /**
  914. * MethodCall ::= ["(" [Values] ")"]
  915. *
  916. * @return mixed[]
  917. *
  918. * @throws AnnotationException
  919. * @throws ReflectionException
  920. */
  921. private function MethodCall(): array
  922. {
  923. $values = [];
  924. if (! $this->lexer->isNextToken(DocLexer::T_OPEN_PARENTHESIS)) {
  925. return $values;
  926. }
  927. $this->match(DocLexer::T_OPEN_PARENTHESIS);
  928. if (! $this->lexer->isNextToken(DocLexer::T_CLOSE_PARENTHESIS)) {
  929. $values = $this->Values();
  930. }
  931. $this->match(DocLexer::T_CLOSE_PARENTHESIS);
  932. return $values;
  933. }
  934. /**
  935. * Values ::= Array | Value {"," Value}* [","]
  936. *
  937. * @return mixed[]
  938. *
  939. * @throws AnnotationException
  940. * @throws ReflectionException
  941. */
  942. private function Values(): array
  943. {
  944. $values = [$this->Value()];
  945. while ($this->lexer->isNextToken(DocLexer::T_COMMA)) {
  946. $this->match(DocLexer::T_COMMA);
  947. if ($this->lexer->isNextToken(DocLexer::T_CLOSE_PARENTHESIS)) {
  948. break;
  949. }
  950. $token = $this->lexer->lookahead;
  951. $value = $this->Value();
  952. $values[] = $value;
  953. }
  954. $namedArguments = [];
  955. $positionalArguments = [];
  956. foreach ($values as $k => $value) {
  957. if (is_object($value) && $value instanceof stdClass) {
  958. $namedArguments[$value->name] = $value->value;
  959. } else {
  960. $positionalArguments[$k] = $value;
  961. }
  962. }
  963. return ['named_arguments' => $namedArguments, 'positional_arguments' => $positionalArguments];
  964. }
  965. /**
  966. * Constant ::= integer | string | float | boolean
  967. *
  968. * @return mixed
  969. *
  970. * @throws AnnotationException
  971. */
  972. private function Constant()
  973. {
  974. $identifier = $this->Identifier();
  975. if (! defined($identifier) && strpos($identifier, '::') !== false && $identifier[0] !== '\\') {
  976. [$className, $const] = explode('::', $identifier);
  977. $pos = strpos($className, '\\');
  978. $alias = ($pos === false) ? $className : substr($className, 0, $pos);
  979. $found = false;
  980. $loweredAlias = strtolower($alias);
  981. switch (true) {
  982. case ! empty($this->namespaces):
  983. foreach ($this->namespaces as $ns) {
  984. if (class_exists($ns . '\\' . $className) || interface_exists($ns . '\\' . $className)) {
  985. $className = $ns . '\\' . $className;
  986. $found = true;
  987. break;
  988. }
  989. }
  990. break;
  991. case isset($this->imports[$loweredAlias]):
  992. $found = true;
  993. $className = ($pos !== false)
  994. ? $this->imports[$loweredAlias] . substr($className, $pos)
  995. : $this->imports[$loweredAlias];
  996. break;
  997. default:
  998. if (isset($this->imports['__NAMESPACE__'])) {
  999. $ns = $this->imports['__NAMESPACE__'];
  1000. if (class_exists($ns . '\\' . $className) || interface_exists($ns . '\\' . $className)) {
  1001. $className = $ns . '\\' . $className;
  1002. $found = true;
  1003. }
  1004. }
  1005. break;
  1006. }
  1007. if ($found) {
  1008. $identifier = $className . '::' . $const;
  1009. }
  1010. }
  1011. /**
  1012. * Checks if identifier ends with ::class and remove the leading backslash if it exists.
  1013. */
  1014. if (
  1015. $this->identifierEndsWithClassConstant($identifier) &&
  1016. ! $this->identifierStartsWithBackslash($identifier)
  1017. ) {
  1018. return substr($identifier, 0, $this->getClassConstantPositionInIdentifier($identifier));
  1019. }
  1020. if ($this->identifierEndsWithClassConstant($identifier) && $this->identifierStartsWithBackslash($identifier)) {
  1021. return substr($identifier, 1, $this->getClassConstantPositionInIdentifier($identifier) - 1);
  1022. }
  1023. if (! defined($identifier)) {
  1024. throw AnnotationException::semanticalErrorConstants($identifier, $this->context);
  1025. }
  1026. return constant($identifier);
  1027. }
  1028. private function identifierStartsWithBackslash(string $identifier): bool
  1029. {
  1030. return $identifier[0] === '\\';
  1031. }
  1032. private function identifierEndsWithClassConstant(string $identifier): bool
  1033. {
  1034. return $this->getClassConstantPositionInIdentifier($identifier) === strlen($identifier) - strlen('::class');
  1035. }
  1036. /** @return int|false */
  1037. private function getClassConstantPositionInIdentifier(string $identifier)
  1038. {
  1039. return stripos($identifier, '::class');
  1040. }
  1041. /**
  1042. * Identifier ::= string
  1043. *
  1044. * @throws AnnotationException
  1045. */
  1046. private function Identifier(): string
  1047. {
  1048. // check if we have an annotation
  1049. if (! $this->lexer->isNextTokenAny(self::$classIdentifiers)) {
  1050. throw $this->syntaxError('namespace separator or identifier');
  1051. }
  1052. $this->lexer->moveNext();
  1053. $className = $this->lexer->token['value'];
  1054. while (
  1055. $this->lexer->lookahead !== null &&
  1056. $this->lexer->lookahead['position'] === ($this->lexer->token['position'] +
  1057. strlen($this->lexer->token['value'])) &&
  1058. $this->lexer->isNextToken(DocLexer::T_NAMESPACE_SEPARATOR)
  1059. ) {
  1060. $this->match(DocLexer::T_NAMESPACE_SEPARATOR);
  1061. $this->matchAny(self::$classIdentifiers);
  1062. $className .= '\\' . $this->lexer->token['value'];
  1063. }
  1064. return $className;
  1065. }
  1066. /**
  1067. * Value ::= PlainValue | FieldAssignment
  1068. *
  1069. * @return mixed
  1070. *
  1071. * @throws AnnotationException
  1072. * @throws ReflectionException
  1073. */
  1074. private function Value()
  1075. {
  1076. $peek = $this->lexer->glimpse();
  1077. if ($peek['type'] === DocLexer::T_EQUALS) {
  1078. return $this->FieldAssignment();
  1079. }
  1080. return $this->PlainValue();
  1081. }
  1082. /**
  1083. * PlainValue ::= integer | string | float | boolean | Array | Annotation
  1084. *
  1085. * @return mixed
  1086. *
  1087. * @throws AnnotationException
  1088. * @throws ReflectionException
  1089. */
  1090. private function PlainValue()
  1091. {
  1092. if ($this->lexer->isNextToken(DocLexer::T_OPEN_CURLY_BRACES)) {
  1093. return $this->Arrayx();
  1094. }
  1095. if ($this->lexer->isNextToken(DocLexer::T_AT)) {
  1096. return $this->Annotation();
  1097. }
  1098. if ($this->lexer->isNextToken(DocLexer::T_IDENTIFIER)) {
  1099. return $this->Constant();
  1100. }
  1101. switch ($this->lexer->lookahead['type']) {
  1102. case DocLexer::T_STRING:
  1103. $this->match(DocLexer::T_STRING);
  1104. return $this->lexer->token['value'];
  1105. case DocLexer::T_INTEGER:
  1106. $this->match(DocLexer::T_INTEGER);
  1107. return (int) $this->lexer->token['value'];
  1108. case DocLexer::T_FLOAT:
  1109. $this->match(DocLexer::T_FLOAT);
  1110. return (float) $this->lexer->token['value'];
  1111. case DocLexer::T_TRUE:
  1112. $this->match(DocLexer::T_TRUE);
  1113. return true;
  1114. case DocLexer::T_FALSE:
  1115. $this->match(DocLexer::T_FALSE);
  1116. return false;
  1117. case DocLexer::T_NULL:
  1118. $this->match(DocLexer::T_NULL);
  1119. return null;
  1120. default:
  1121. throw $this->syntaxError('PlainValue');
  1122. }
  1123. }
  1124. /**
  1125. * FieldAssignment ::= FieldName "=" PlainValue
  1126. * FieldName ::= identifier
  1127. *
  1128. * @throws AnnotationException
  1129. * @throws ReflectionException
  1130. */
  1131. private function FieldAssignment(): stdClass
  1132. {
  1133. $this->match(DocLexer::T_IDENTIFIER);
  1134. $fieldName = $this->lexer->token['value'];
  1135. $this->match(DocLexer::T_EQUALS);
  1136. $item = new stdClass();
  1137. $item->name = $fieldName;
  1138. $item->value = $this->PlainValue();
  1139. return $item;
  1140. }
  1141. /**
  1142. * Array ::= "{" ArrayEntry {"," ArrayEntry}* [","] "}"
  1143. *
  1144. * @return mixed[]
  1145. *
  1146. * @throws AnnotationException
  1147. * @throws ReflectionException
  1148. */
  1149. private function Arrayx(): array
  1150. {
  1151. $array = $values = [];
  1152. $this->match(DocLexer::T_OPEN_CURLY_BRACES);
  1153. // If the array is empty, stop parsing and return.
  1154. if ($this->lexer->isNextToken(DocLexer::T_CLOSE_CURLY_BRACES)) {
  1155. $this->match(DocLexer::T_CLOSE_CURLY_BRACES);
  1156. return $array;
  1157. }
  1158. $values[] = $this->ArrayEntry();
  1159. while ($this->lexer->isNextToken(DocLexer::T_COMMA)) {
  1160. $this->match(DocLexer::T_COMMA);
  1161. // optional trailing comma
  1162. if ($this->lexer->isNextToken(DocLexer::T_CLOSE_CURLY_BRACES)) {
  1163. break;
  1164. }
  1165. $values[] = $this->ArrayEntry();
  1166. }
  1167. $this->match(DocLexer::T_CLOSE_CURLY_BRACES);
  1168. foreach ($values as $value) {
  1169. [$key, $val] = $value;
  1170. if ($key !== null) {
  1171. $array[$key] = $val;
  1172. } else {
  1173. $array[] = $val;
  1174. }
  1175. }
  1176. return $array;
  1177. }
  1178. /**
  1179. * ArrayEntry ::= Value | KeyValuePair
  1180. * KeyValuePair ::= Key ("=" | ":") PlainValue | Constant
  1181. * Key ::= string | integer | Constant
  1182. *
  1183. * @phpstan-return array{mixed, mixed}
  1184. *
  1185. * @throws AnnotationException
  1186. * @throws ReflectionException
  1187. */
  1188. private function ArrayEntry(): array
  1189. {
  1190. $peek = $this->lexer->glimpse();
  1191. if (
  1192. $peek['type'] === DocLexer::T_EQUALS
  1193. || $peek['type'] === DocLexer::T_COLON
  1194. ) {
  1195. if ($this->lexer->isNextToken(DocLexer::T_IDENTIFIER)) {
  1196. $key = $this->Constant();
  1197. } else {
  1198. $this->matchAny([DocLexer::T_INTEGER, DocLexer::T_STRING]);
  1199. $key = $this->lexer->token['value'];
  1200. }
  1201. $this->matchAny([DocLexer::T_EQUALS, DocLexer::T_COLON]);
  1202. return [$key, $this->PlainValue()];
  1203. }
  1204. return [null, $this->Value()];
  1205. }
  1206. /**
  1207. * Checks whether the given $name matches any ignored annotation name or namespace
  1208. */
  1209. private function isIgnoredAnnotation(string $name): bool
  1210. {
  1211. if ($this->ignoreNotImportedAnnotations || isset($this->ignoredAnnotationNames[$name])) {
  1212. return true;
  1213. }
  1214. foreach (array_keys($this->ignoredAnnotationNamespaces) as $ignoredAnnotationNamespace) {
  1215. $ignoredAnnotationNamespace = rtrim($ignoredAnnotationNamespace, '\\') . '\\';
  1216. if (stripos(rtrim($name, '\\') . '\\', $ignoredAnnotationNamespace) === 0) {
  1217. return true;
  1218. }
  1219. }
  1220. return false;
  1221. }
  1222. /**
  1223. * Resolve positional arguments (without name) to named ones
  1224. *
  1225. * @param array<string,mixed> $arguments
  1226. *
  1227. * @return array<string,mixed>
  1228. */
  1229. private function resolvePositionalValues(array $arguments, string $name): array
  1230. {
  1231. $positionalArguments = $arguments['positional_arguments'] ?? [];
  1232. $values = $arguments['named_arguments'] ?? [];
  1233. if (
  1234. self::$annotationMetadata[$name]['has_named_argument_constructor']
  1235. && self::$annotationMetadata[$name]['default_property'] !== null
  1236. ) {
  1237. // We must ensure that we don't have positional arguments after named ones
  1238. $positions = array_keys($positionalArguments);
  1239. $lastPosition = null;
  1240. foreach ($positions as $position) {
  1241. if (
  1242. ($lastPosition === null && $position !== 0) ||
  1243. ($lastPosition !== null && $position !== $lastPosition + 1)
  1244. ) {
  1245. throw $this->syntaxError('Positional arguments after named arguments is not allowed');
  1246. }
  1247. $lastPosition = $position;
  1248. }
  1249. foreach (self::$annotationMetadata[$name]['constructor_args'] as $property => $parameter) {
  1250. $position = $parameter['position'];
  1251. if (isset($values[$property]) || ! isset($positionalArguments[$position])) {
  1252. continue;
  1253. }
  1254. $values[$property] = $positionalArguments[$position];
  1255. }
  1256. } else {
  1257. if (count($positionalArguments) > 0 && ! isset($values['value'])) {
  1258. if (count($positionalArguments) === 1) {
  1259. $value = array_pop($positionalArguments);
  1260. } else {
  1261. $value = array_values($positionalArguments);
  1262. }
  1263. $values['value'] = $value;
  1264. }
  1265. }
  1266. return $values;
  1267. }
  1268. /**
  1269. * Try to instantiate the annotation and catch and process any exceptions related to failure
  1270. *
  1271. * @param class-string $name
  1272. * @param array<string,mixed> $arguments
  1273. *
  1274. * @return object
  1275. *
  1276. * @throws AnnotationException
  1277. */
  1278. private function instantiateAnnotiation(string $originalName, string $context, string $name, array $arguments)
  1279. {
  1280. try {
  1281. return new $name(...$arguments);
  1282. } catch (Throwable $exception) {
  1283. throw AnnotationException::creationError(
  1284. sprintf(
  1285. 'An error occurred while instantiating the annotation @%s declared on %s: "%s".',
  1286. $originalName,
  1287. $context,
  1288. $exception->getMessage()
  1289. ),
  1290. $exception
  1291. );
  1292. }
  1293. }
  1294. }