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