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