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.
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>.
20 namespace Doctrine\Common\Annotations;
22 use Doctrine\Common\Annotations\Annotation\Attribute;
24 use Doctrine\Common\Annotations\Annotation\Enum;
25 use Doctrine\Common\Annotations\Annotation\Target;
26 use Doctrine\Common\Annotations\Annotation\Attributes;
29 * A parser for docblock annotations.
31 * It is strongly discouraged to change the default annotation parsing process.
33 * @author Benjamin Eberlei <kontakt@beberlei.de>
34 * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
35 * @author Jonathan Wage <jonwage@gmail.com>
36 * @author Roman Borschel <roman@code-factory.org>
37 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
38 * @author Fabio B. Silva <fabio.bat.silva@gmail.com>
43 * An array of all valid tokens for a class name.
47 private static $classIdentifiers = array(
48 DocLexer::T_IDENTIFIER,
57 * @var \Doctrine\Common\Annotations\DocLexer
62 * Current target context.
69 * Doc parser used to collect annotation target.
71 * @var \Doctrine\Common\Annotations\DocParser
73 private static $metadataParser;
76 * Flag to control if the current annotation is nested or not.
80 private $isNestedAnnotation = false;
83 * Hashmap containing all use-statements that are to be used when parsing
84 * the given doc block.
88 private $imports = array();
91 * This hashmap is used internally to cache results of class_exists()
96 private $classExists = array();
99 * Whether annotations that have not been imported should be ignored.
103 private $ignoreNotImportedAnnotations = false;
106 * An array of default namespaces if operating in simple mode.
110 private $namespaces = array();
113 * A list with annotations that are not causing exceptions when not resolved to an annotation class.
115 * The names must be the raw names as used in the class, not the fully qualified
118 * @var bool[] indexed by annotation name
120 private $ignoredAnnotationNames = array();
123 * A list with annotations in namespaced format
124 * that are not causing exceptions when not resolved to an annotation class.
126 * @var bool[] indexed by namespace name
128 private $ignoredAnnotationNamespaces = array();
133 private $context = '';
136 * Hash-map for caching annotation metadata.
140 private static $annotationMetadata = array(
141 'Doctrine\Common\Annotations\Annotation\Target' => array(
142 'is_annotation' => true,
143 'has_constructor' => true,
144 'properties' => array(),
145 'targets_literal' => 'ANNOTATION_CLASS',
146 'targets' => Target::TARGET_CLASS,
147 'default_property' => 'value',
148 'attribute_types' => array(
152 'array_type'=>'string',
153 'value' =>'array<string>'
157 'Doctrine\Common\Annotations\Annotation\Attribute' => array(
158 'is_annotation' => true,
159 'has_constructor' => false,
160 'targets_literal' => 'ANNOTATION_ANNOTATION',
161 'targets' => Target::TARGET_ANNOTATION,
162 'default_property' => 'name',
163 'properties' => array(
166 'required' => 'required'
168 'attribute_types' => array(
186 'Doctrine\Common\Annotations\Annotation\Attributes' => array(
187 'is_annotation' => true,
188 'has_constructor' => false,
189 'targets_literal' => 'ANNOTATION_CLASS',
190 'targets' => Target::TARGET_CLASS,
191 'default_property' => 'value',
192 'properties' => array(
195 'attribute_types' => array(
199 'array_type'=>'Doctrine\Common\Annotations\Annotation\Attribute',
200 'value' =>'array<Doctrine\Common\Annotations\Annotation\Attribute>'
204 'Doctrine\Common\Annotations\Annotation\Enum' => array(
205 'is_annotation' => true,
206 'has_constructor' => true,
207 'targets_literal' => 'ANNOTATION_PROPERTY',
208 'targets' => Target::TARGET_PROPERTY,
209 'default_property' => 'value',
210 'properties' => array(
213 'attribute_types' => array(
227 * Hash-map for handle types declaration.
231 private static $typeMap = array(
234 // allow uppercase Boolean in honor of George Boole
235 'Boolean' => 'boolean',
240 * Constructs a new DocParser.
242 public function __construct()
244 $this->lexer = new DocLexer;
248 * Sets the annotation names that are ignored during the parsing process.
250 * The names are supposed to be the raw names as used in the class, not the
251 * fully qualified class names.
253 * @param bool[] $names indexed by annotation name
257 public function setIgnoredAnnotationNames(array $names)
259 $this->ignoredAnnotationNames = $names;
263 * Sets the annotation namespaces that are ignored during the parsing process.
265 * @param bool[] $ignoredAnnotationNamespaces indexed by annotation namespace name
269 public function setIgnoredAnnotationNamespaces($ignoredAnnotationNamespaces)
271 $this->ignoredAnnotationNamespaces = $ignoredAnnotationNamespaces;
275 * Sets ignore on not-imported annotations.
277 * @param boolean $bool
281 public function setIgnoreNotImportedAnnotations($bool)
283 $this->ignoreNotImportedAnnotations = (boolean) $bool;
287 * Sets the default namespaces.
289 * @param string $namespace
293 * @throws \RuntimeException
295 public function addNamespace($namespace)
297 if ($this->imports) {
298 throw new \RuntimeException('You must either use addNamespace(), or setImports(), but not both.');
301 $this->namespaces[] = $namespace;
307 * @param array $imports
311 * @throws \RuntimeException
313 public function setImports(array $imports)
315 if ($this->namespaces) {
316 throw new \RuntimeException('You must either use addNamespace(), or setImports(), but not both.');
319 $this->imports = $imports;
323 * Sets current target context as bitmask.
325 * @param integer $target
329 public function setTarget($target)
331 $this->target = $target;
335 * Parses the given docblock string for annotations.
337 * @param string $input The docblock string to parse.
338 * @param string $context The parsing context.
340 * @return array Array of annotations. If no annotations are found, an empty array is returned.
342 public function parse($input, $context = '')
344 $pos = $this->findInitialTokenPosition($input);
349 $this->context = $context;
351 $this->lexer->setInput(trim(substr($input, $pos), '* /'));
352 $this->lexer->moveNext();
354 return $this->Annotations();
358 * Finds the first valid annotation
360 * @param string $input The docblock string to parse
364 private function findInitialTokenPosition($input)
368 // search for first valid annotation
369 while (($pos = strpos($input, '@', $pos)) !== false) {
370 $preceding = substr($input, $pos - 1, 1);
372 // if the @ is preceded by a space, a tab or * it is valid
373 if ($pos === 0 || $preceding === ' ' || $preceding === '*' || $preceding === "\t") {
384 * Attempts to match the given token with the current lookahead token.
385 * If they match, updates the lookahead token; otherwise raises a syntax error.
387 * @param integer $token Type of token.
389 * @return boolean True if tokens match; false otherwise.
391 private function match($token)
393 if ( ! $this->lexer->isNextToken($token) ) {
394 $this->syntaxError($this->lexer->getLiteral($token));
397 return $this->lexer->moveNext();
401 * Attempts to match the current lookahead token with any of the given tokens.
403 * If any of them matches, this method updates the lookahead token; otherwise
404 * a syntax error is raised.
406 * @param array $tokens
410 private function matchAny(array $tokens)
412 if ( ! $this->lexer->isNextTokenAny($tokens)) {
413 $this->syntaxError(implode(' or ', array_map(array($this->lexer, 'getLiteral'), $tokens)));
416 return $this->lexer->moveNext();
420 * Generates a new syntax error.
422 * @param string $expected Expected string.
423 * @param array|null $token Optional token.
427 * @throws AnnotationException
429 private function syntaxError($expected, $token = null)
431 if ($token === null) {
432 $token = $this->lexer->lookahead;
435 $message = sprintf('Expected %s, got ', $expected);
436 $message .= ($this->lexer->lookahead === null)
438 : sprintf("'%s' at position %s", $token['value'], $token['position']);
440 if (strlen($this->context)) {
441 $message .= ' in ' . $this->context;
446 throw AnnotationException::syntaxError($message);
450 * Attempts to check if a class exists or not. This never goes through the PHP autoloading mechanism
451 * but uses the {@link AnnotationRegistry} to load classes.
453 * @param string $fqcn
457 private function classExists($fqcn)
459 if (isset($this->classExists[$fqcn])) {
460 return $this->classExists[$fqcn];
463 // first check if the class already exists, maybe loaded through another AnnotationReader
464 if (class_exists($fqcn, false)) {
465 return $this->classExists[$fqcn] = true;
468 // final check, does this class exist?
469 return $this->classExists[$fqcn] = AnnotationRegistry::loadAnnotationClass($fqcn);
473 * Collects parsing metadata for a given annotation class
475 * @param string $name The annotation name
479 private function collectAnnotationMetadata($name)
481 if (self::$metadataParser === null) {
482 self::$metadataParser = new self();
484 self::$metadataParser->setIgnoreNotImportedAnnotations(true);
485 self::$metadataParser->setIgnoredAnnotationNames($this->ignoredAnnotationNames);
486 self::$metadataParser->setImports(array(
487 'enum' => 'Doctrine\Common\Annotations\Annotation\Enum',
488 'target' => 'Doctrine\Common\Annotations\Annotation\Target',
489 'attribute' => 'Doctrine\Common\Annotations\Annotation\Attribute',
490 'attributes' => 'Doctrine\Common\Annotations\Annotation\Attributes'
493 AnnotationRegistry::registerFile(__DIR__ . '/Annotation/Enum.php');
494 AnnotationRegistry::registerFile(__DIR__ . '/Annotation/Target.php');
495 AnnotationRegistry::registerFile(__DIR__ . '/Annotation/Attribute.php');
496 AnnotationRegistry::registerFile(__DIR__ . '/Annotation/Attributes.php');
499 $class = new \ReflectionClass($name);
500 $docComment = $class->getDocComment();
502 // Sets default values for annotation metadata
504 'default_property' => null,
505 'has_constructor' => (null !== $constructor = $class->getConstructor()) && $constructor->getNumberOfParameters() > 0,
506 'properties' => array(),
507 'property_types' => array(),
508 'attribute_types' => array(),
509 'targets_literal' => null,
510 'targets' => Target::TARGET_ALL,
511 'is_annotation' => false !== strpos($docComment, '@Annotation'),
514 // verify that the class is really meant to be an annotation
515 if ($metadata['is_annotation']) {
516 self::$metadataParser->setTarget(Target::TARGET_CLASS);
518 foreach (self::$metadataParser->parse($docComment, 'class @' . $name) as $annotation) {
519 if ($annotation instanceof Target) {
520 $metadata['targets'] = $annotation->targets;
521 $metadata['targets_literal'] = $annotation->literal;
526 if ($annotation instanceof Attributes) {
527 foreach ($annotation->value as $attribute) {
528 $this->collectAttributeTypeMetadata($metadata, $attribute);
533 // if not has a constructor will inject values into public properties
534 if (false === $metadata['has_constructor']) {
535 // collect all public properties
536 foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
537 $metadata['properties'][$property->name] = $property->name;
539 if (false === ($propertyComment = $property->getDocComment())) {
543 $attribute = new Attribute();
545 $attribute->required = (false !== strpos($propertyComment, '@Required'));
546 $attribute->name = $property->name;
547 $attribute->type = (false !== strpos($propertyComment, '@var') && preg_match('/@var\s+([^\s]+)/',$propertyComment, $matches))
551 $this->collectAttributeTypeMetadata($metadata, $attribute);
553 // checks if the property has @Enum
554 if (false !== strpos($propertyComment, '@Enum')) {
555 $context = 'property ' . $class->name . "::\$" . $property->name;
557 self::$metadataParser->setTarget(Target::TARGET_PROPERTY);
559 foreach (self::$metadataParser->parse($propertyComment, $context) as $annotation) {
560 if ( ! $annotation instanceof Enum) {
564 $metadata['enum'][$property->name]['value'] = $annotation->value;
565 $metadata['enum'][$property->name]['literal'] = ( ! empty($annotation->literal))
566 ? $annotation->literal
567 : $annotation->value;
572 // choose the first property as default property
573 $metadata['default_property'] = reset($metadata['properties']);
577 self::$annotationMetadata[$name] = $metadata;
581 * Collects parsing metadata for a given attribute.
583 * @param array $metadata
584 * @param Attribute $attribute
588 private function collectAttributeTypeMetadata(&$metadata, Attribute $attribute)
590 // handle internal type declaration
591 $type = isset(self::$typeMap[$attribute->type])
592 ? self::$typeMap[$attribute->type]
595 // handle the case if the property type is mixed
596 if ('mixed' === $type) {
602 // Checks if the property has array<type>
603 case (false !== $pos = strpos($type, '<')):
604 $arrayType = substr($type, $pos + 1, -1);
607 if (isset(self::$typeMap[$arrayType])) {
608 $arrayType = self::$typeMap[$arrayType];
611 $metadata['attribute_types'][$attribute->name]['array_type'] = $arrayType;
614 // Checks if the property has type[]
615 case (false !== $pos = strrpos($type, '[')):
616 $arrayType = substr($type, 0, $pos);
619 if (isset(self::$typeMap[$arrayType])) {
620 $arrayType = self::$typeMap[$arrayType];
623 $metadata['attribute_types'][$attribute->name]['array_type'] = $arrayType;
627 $metadata['attribute_types'][$attribute->name]['type'] = $type;
628 $metadata['attribute_types'][$attribute->name]['value'] = $attribute->type;
629 $metadata['attribute_types'][$attribute->name]['required'] = $attribute->required;
633 * Annotations ::= Annotation {[ "*" ]* [Annotation]}*
637 private function Annotations()
639 $annotations = array();
641 while (null !== $this->lexer->lookahead) {
642 if (DocLexer::T_AT !== $this->lexer->lookahead['type']) {
643 $this->lexer->moveNext();
647 // make sure the @ is preceded by non-catchable pattern
648 if (null !== $this->lexer->token && $this->lexer->lookahead['position'] === $this->lexer->token['position'] + strlen($this->lexer->token['value'])) {
649 $this->lexer->moveNext();
653 // make sure the @ is followed by either a namespace separator, or
654 // an identifier token
655 if ((null === $peek = $this->lexer->glimpse())
656 || (DocLexer::T_NAMESPACE_SEPARATOR !== $peek['type'] && !in_array($peek['type'], self::$classIdentifiers, true))
657 || $peek['position'] !== $this->lexer->lookahead['position'] + 1) {
658 $this->lexer->moveNext();
662 $this->isNestedAnnotation = false;
663 if (false !== $annot = $this->Annotation()) {
664 $annotations[] = $annot;
672 * Annotation ::= "@" AnnotationName MethodCall
673 * AnnotationName ::= QualifiedName | SimpleName
674 * QualifiedName ::= NameSpacePart "\" {NameSpacePart "\"}* SimpleName
675 * NameSpacePart ::= identifier | null | false | true
676 * SimpleName ::= identifier | null | false | true
678 * @return mixed False if it is not a valid annotation.
680 * @throws AnnotationException
682 private function Annotation()
684 $this->match(DocLexer::T_AT);
686 // check if we have an annotation
687 $name = $this->Identifier();
689 // only process names which are not fully qualified, yet
690 // fully qualified names must start with a \
691 $originalName = $name;
693 if ('\\' !== $name[0]) {
694 $pos = strpos($name, '\\');
695 $alias = (false === $pos)? $name : substr($name, 0, $pos);
697 $loweredAlias = strtolower($alias);
699 if ($this->namespaces) {
700 foreach ($this->namespaces as $namespace) {
701 if ($this->classExists($namespace.'\\'.$name)) {
702 $name = $namespace.'\\'.$name;
707 } elseif (isset($this->imports[$loweredAlias])) {
709 $name = (false !== $pos)
710 ? $this->imports[$loweredAlias] . substr($name, $pos)
711 : $this->imports[$loweredAlias];
712 } elseif ( ! isset($this->ignoredAnnotationNames[$name])
713 && isset($this->imports['__NAMESPACE__'])
714 && $this->classExists($this->imports['__NAMESPACE__'] . '\\' . $name)
716 $name = $this->imports['__NAMESPACE__'].'\\'.$name;
718 } elseif (! isset($this->ignoredAnnotationNames[$name]) && $this->classExists($name)) {
723 if ($this->isIgnoredAnnotation($name)) {
727 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));
731 $name = ltrim($name,'\\');
733 if ( ! $this->classExists($name)) {
734 throw AnnotationException::semanticalError(sprintf('The annotation "@%s" in %s does not exist, or could not be auto-loaded.', $name, $this->context));
737 // at this point, $name contains the fully qualified class name of the
738 // annotation, and it is also guaranteed that this class exists, and
742 // collects the metadata annotation only if there is not yet
743 if ( ! isset(self::$annotationMetadata[$name])) {
744 $this->collectAnnotationMetadata($name);
747 // verify that the class is really meant to be an annotation and not just any ordinary class
748 if (self::$annotationMetadata[$name]['is_annotation'] === false) {
749 if ($this->ignoreNotImportedAnnotations || isset($this->ignoredAnnotationNames[$originalName])) {
753 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));
756 //if target is nested annotation
757 $target = $this->isNestedAnnotation ? Target::TARGET_ANNOTATION : $this->target;
759 // Next will be nested
760 $this->isNestedAnnotation = true;
762 //if annotation does not support current target
763 if (0 === (self::$annotationMetadata[$name]['targets'] & $target) && $target) {
764 throw AnnotationException::semanticalError(
765 sprintf('Annotation @%s is not allowed to be declared on %s. You may only use this annotation on these code elements: %s.',
766 $originalName, $this->context, self::$annotationMetadata[$name]['targets_literal'])
770 $values = $this->MethodCall();
772 if (isset(self::$annotationMetadata[$name]['enum'])) {
773 // checks all declared attributes
774 foreach (self::$annotationMetadata[$name]['enum'] as $property => $enum) {
775 // checks if the attribute is a valid enumerator
776 if (isset($values[$property]) && ! in_array($values[$property], $enum['value'])) {
777 throw AnnotationException::enumeratorError($property, $name, $this->context, $enum['literal'], $values[$property]);
782 // checks all declared attributes
783 foreach (self::$annotationMetadata[$name]['attribute_types'] as $property => $type) {
784 if ($property === self::$annotationMetadata[$name]['default_property']
785 && !isset($values[$property]) && isset($values['value'])) {
789 // handle a not given attribute or null value
790 if (!isset($values[$property])) {
791 if ($type['required']) {
792 throw AnnotationException::requiredError($property, $originalName, $this->context, 'a(n) '.$type['value']);
798 if ($type['type'] === 'array') {
799 // handle the case of a single value
800 if ( ! is_array($values[$property])) {
801 $values[$property] = array($values[$property]);
804 // checks if the attribute has array type declaration, such as "array<string>"
805 if (isset($type['array_type'])) {
806 foreach ($values[$property] as $item) {
807 if (gettype($item) !== $type['array_type'] && !$item instanceof $type['array_type']) {
808 throw AnnotationException::attributeTypeError($property, $originalName, $this->context, 'either a(n) '.$type['array_type'].', or an array of '.$type['array_type'].'s', $item);
812 } elseif (gettype($values[$property]) !== $type['type'] && !$values[$property] instanceof $type['type']) {
813 throw AnnotationException::attributeTypeError($property, $originalName, $this->context, 'a(n) '.$type['value'], $values[$property]);
817 // check if the annotation expects values via the constructor,
818 // or directly injected into public properties
819 if (self::$annotationMetadata[$name]['has_constructor'] === true) {
820 return new $name($values);
823 $instance = new $name();
825 foreach ($values as $property => $value) {
826 if (!isset(self::$annotationMetadata[$name]['properties'][$property])) {
827 if ('value' !== $property) {
828 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'])));
831 // handle the case if the property has no annotations
832 if ( ! $property = self::$annotationMetadata[$name]['default_property']) {
833 throw AnnotationException::creationError(sprintf('The annotation @%s declared on %s does not accept any values, but got %s.', $originalName, $this->context, json_encode($values)));
837 $instance->{$property} = $value;
844 * MethodCall ::= ["(" [Values] ")"]
848 private function MethodCall()
852 if ( ! $this->lexer->isNextToken(DocLexer::T_OPEN_PARENTHESIS)) {
856 $this->match(DocLexer::T_OPEN_PARENTHESIS);
858 if ( ! $this->lexer->isNextToken(DocLexer::T_CLOSE_PARENTHESIS)) {
859 $values = $this->Values();
862 $this->match(DocLexer::T_CLOSE_PARENTHESIS);
868 * Values ::= Array | Value {"," Value}* [","]
872 private function Values()
874 $values = array($this->Value());
876 while ($this->lexer->isNextToken(DocLexer::T_COMMA)) {
877 $this->match(DocLexer::T_COMMA);
879 if ($this->lexer->isNextToken(DocLexer::T_CLOSE_PARENTHESIS)) {
883 $token = $this->lexer->lookahead;
884 $value = $this->Value();
886 if ( ! is_object($value) && ! is_array($value)) {
887 $this->syntaxError('Value', $token);
893 foreach ($values as $k => $value) {
894 if (is_object($value) && $value instanceof \stdClass) {
895 $values[$value->name] = $value->value;
896 } else if ( ! isset($values['value'])){
897 $values['value'] = $value;
899 if ( ! is_array($values['value'])) {
900 $values['value'] = array($values['value']);
903 $values['value'][] = $value;
913 * Constant ::= integer | string | float | boolean
917 * @throws AnnotationException
919 private function Constant()
921 $identifier = $this->Identifier();
923 if ( ! defined($identifier) && false !== strpos($identifier, '::') && '\\' !== $identifier[0]) {
924 list($className, $const) = explode('::', $identifier);
926 $pos = strpos($className, '\\');
927 $alias = (false === $pos) ? $className : substr($className, 0, $pos);
929 $loweredAlias = strtolower($alias);
932 case !empty ($this->namespaces):
933 foreach ($this->namespaces as $ns) {
934 if (class_exists($ns.'\\'.$className) || interface_exists($ns.'\\'.$className)) {
935 $className = $ns.'\\'.$className;
942 case isset($this->imports[$loweredAlias]):
944 $className = (false !== $pos)
945 ? $this->imports[$loweredAlias] . substr($className, $pos)
946 : $this->imports[$loweredAlias];
950 if(isset($this->imports['__NAMESPACE__'])) {
951 $ns = $this->imports['__NAMESPACE__'];
953 if (class_exists($ns.'\\'.$className) || interface_exists($ns.'\\'.$className)) {
954 $className = $ns.'\\'.$className;
962 $identifier = $className . '::' . $const;
966 // checks if identifier ends with ::class, \strlen('::class') === 7
967 $classPos = stripos($identifier, '::class');
968 if ($classPos === strlen($identifier) - 7) {
969 return substr($identifier, 0, $classPos);
972 if (!defined($identifier)) {
973 throw AnnotationException::semanticalErrorConstants($identifier, $this->context);
976 return constant($identifier);
980 * Identifier ::= string
984 private function Identifier()
986 // check if we have an annotation
987 if ( ! $this->lexer->isNextTokenAny(self::$classIdentifiers)) {
988 $this->syntaxError('namespace separator or identifier');
991 $this->lexer->moveNext();
993 $className = $this->lexer->token['value'];
995 while ($this->lexer->lookahead['position'] === ($this->lexer->token['position'] + strlen($this->lexer->token['value']))
996 && $this->lexer->isNextToken(DocLexer::T_NAMESPACE_SEPARATOR)) {
998 $this->match(DocLexer::T_NAMESPACE_SEPARATOR);
999 $this->matchAny(self::$classIdentifiers);
1001 $className .= '\\' . $this->lexer->token['value'];
1008 * Value ::= PlainValue | FieldAssignment
1012 private function Value()
1014 $peek = $this->lexer->glimpse();
1016 if (DocLexer::T_EQUALS === $peek['type']) {
1017 return $this->FieldAssignment();
1020 return $this->PlainValue();
1024 * PlainValue ::= integer | string | float | boolean | Array | Annotation
1028 private function PlainValue()
1030 if ($this->lexer->isNextToken(DocLexer::T_OPEN_CURLY_BRACES)) {
1031 return $this->Arrayx();
1034 if ($this->lexer->isNextToken(DocLexer::T_AT)) {
1035 return $this->Annotation();
1038 if ($this->lexer->isNextToken(DocLexer::T_IDENTIFIER)) {
1039 return $this->Constant();
1042 switch ($this->lexer->lookahead['type']) {
1043 case DocLexer::T_STRING:
1044 $this->match(DocLexer::T_STRING);
1045 return $this->lexer->token['value'];
1047 case DocLexer::T_INTEGER:
1048 $this->match(DocLexer::T_INTEGER);
1049 return (int)$this->lexer->token['value'];
1051 case DocLexer::T_FLOAT:
1052 $this->match(DocLexer::T_FLOAT);
1053 return (float)$this->lexer->token['value'];
1055 case DocLexer::T_TRUE:
1056 $this->match(DocLexer::T_TRUE);
1059 case DocLexer::T_FALSE:
1060 $this->match(DocLexer::T_FALSE);
1063 case DocLexer::T_NULL:
1064 $this->match(DocLexer::T_NULL);
1068 $this->syntaxError('PlainValue');
1073 * FieldAssignment ::= FieldName "=" PlainValue
1074 * FieldName ::= identifier
1078 private function FieldAssignment()
1080 $this->match(DocLexer::T_IDENTIFIER);
1081 $fieldName = $this->lexer->token['value'];
1083 $this->match(DocLexer::T_EQUALS);
1085 $item = new \stdClass();
1086 $item->name = $fieldName;
1087 $item->value = $this->PlainValue();
1093 * Array ::= "{" ArrayEntry {"," ArrayEntry}* [","] "}"
1097 private function Arrayx()
1099 $array = $values = array();
1101 $this->match(DocLexer::T_OPEN_CURLY_BRACES);
1103 // If the array is empty, stop parsing and return.
1104 if ($this->lexer->isNextToken(DocLexer::T_CLOSE_CURLY_BRACES)) {
1105 $this->match(DocLexer::T_CLOSE_CURLY_BRACES);
1110 $values[] = $this->ArrayEntry();
1112 while ($this->lexer->isNextToken(DocLexer::T_COMMA)) {
1113 $this->match(DocLexer::T_COMMA);
1115 // optional trailing comma
1116 if ($this->lexer->isNextToken(DocLexer::T_CLOSE_CURLY_BRACES)) {
1120 $values[] = $this->ArrayEntry();
1123 $this->match(DocLexer::T_CLOSE_CURLY_BRACES);
1125 foreach ($values as $value) {
1126 list ($key, $val) = $value;
1128 if ($key !== null) {
1129 $array[$key] = $val;
1139 * ArrayEntry ::= Value | KeyValuePair
1140 * KeyValuePair ::= Key ("=" | ":") PlainValue | Constant
1141 * Key ::= string | integer | Constant
1145 private function ArrayEntry()
1147 $peek = $this->lexer->glimpse();
1149 if (DocLexer::T_EQUALS === $peek['type']
1150 || DocLexer::T_COLON === $peek['type']) {
1152 if ($this->lexer->isNextToken(DocLexer::T_IDENTIFIER)) {
1153 $key = $this->Constant();
1155 $this->matchAny(array(DocLexer::T_INTEGER, DocLexer::T_STRING));
1156 $key = $this->lexer->token['value'];
1159 $this->matchAny(array(DocLexer::T_EQUALS, DocLexer::T_COLON));
1161 return array($key, $this->PlainValue());
1164 return array(null, $this->Value());
1168 * Checks whether the given $name matches any ignored annotation name or namespace
1170 * @param string $name
1174 private function isIgnoredAnnotation($name)
1176 if ($this->ignoreNotImportedAnnotations || isset($this->ignoredAnnotationNames[$name])) {
1180 foreach (array_keys($this->ignoredAnnotationNamespaces) as $ignoredAnnotationNamespace) {
1181 $ignoredAnnotationNamespace = rtrim($ignoredAnnotationNamespace, '\\') . '\\';
1183 if (0 === stripos(rtrim($name, '\\') . '\\', $ignoredAnnotationNamespace)) {