Passed
Push — master ( bbca16...640395 )
by Marco
04:44 queued 10s
created

DocParser::setTarget()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Doctrine\Annotations;
4
5
use Doctrine\Annotations\Annotation\Attribute;
6
use Doctrine\Annotations\Metadata\AnnotationTarget;
7
use Doctrine\Annotations\Metadata\Builder\AnnotationMetadataBuilder;
8
use Doctrine\Annotations\Metadata\Builder\PropertyMetadataBuilder;
9
use Doctrine\Annotations\Metadata\InternalAnnotations;
10
use Doctrine\Annotations\Metadata\MetadataCollection;
11
use Doctrine\Annotations\Metadata\TransientMetadataCollection;
12
use ReflectionClass;
13
use Doctrine\Annotations\Annotation\Enum;
14
use Doctrine\Annotations\Annotation\Target;
15
use Doctrine\Annotations\Annotation\Attributes;
16
use function array_key_exists;
17
use function array_keys;
18
19
/**
20
 * A parser for docblock annotations.
21
 *
22
 * It is strongly discouraged to change the default annotation parsing process.
23
 *
24
 * @author Benjamin Eberlei <[email protected]>
25
 * @author Guilherme Blanco <[email protected]>
26
 * @author Jonathan Wage <[email protected]>
27
 * @author Roman Borschel <[email protected]>
28
 * @author Johannes M. Schmitt <[email protected]>
29
 * @author Fabio B. Silva <[email protected]>
30
 */
31
final class DocParser
32
{
33
    /**
34
     * An array of all valid tokens for a class name.
35
     *
36
     * @var array
37
     */
38
    private static $classIdentifiers = [
39
        DocLexer::T_IDENTIFIER,
40
        DocLexer::T_TRUE,
41
        DocLexer::T_FALSE,
42
        DocLexer::T_NULL
43
    ];
44
45
    /**
46
     * The lexer.
47
     *
48
     * @var \Doctrine\Annotations\DocLexer
49
     */
50
    private $lexer;
51
52
    /**
53
     * Current target context.
54
     *
55
     * @var integer
56
     */
57
    private $target;
58
59
    /**
60
     * Doc parser used to collect annotation target.
61
     *
62
     * @var \Doctrine\Annotations\DocParser
63
     */
64
    private static $metadataParser;
65
66
    /**
67
     * Flag to control if the current annotation is nested or not.
68
     *
69
     * @var boolean
70
     */
71
    private $isNestedAnnotation = false;
72
73
    /**
74
     * Hashmap containing all use-statements that are to be used when parsing
75
     * the given doc block.
76
     *
77
     * @var array
78
     */
79
    private $imports = [];
80
81
    /**
82
     * This hashmap is used internally to cache results of class_exists()
83
     * look-ups.
84
     *
85
     * @var array
86
     */
87
    private $classExists = [];
88
89
    /**
90
     * Whether annotations that have not been imported should be ignored.
91
     *
92
     * @var boolean
93
     */
94
    private $ignoreNotImportedAnnotations = false;
95
96
    /**
97
     * An array of default namespaces if operating in simple mode.
98
     *
99
     * @var string[]
100
     */
101
    private $namespaces = [];
102
103
    /**
104
     * A list with annotations that are not causing exceptions when not resolved to an annotation class.
105
     *
106
     * The names must be the raw names as used in the class, not the fully qualified
107
     * class names.
108
     *
109
     * @var bool[] indexed by annotation name
110
     */
111
    private $ignoredAnnotationNames = [];
112
113
    /**
114
     * A list with annotations in namespaced format
115
     * that are not causing exceptions when not resolved to an annotation class.
116
     *
117
     * @var bool[] indexed by namespace name
118
     */
119
    private $ignoredAnnotationNamespaces = [];
120
121
    /**
122
     * @var string
123
     */
124
    private $context = '';
125
126
    /**
127
     * Hash-map for caching annotation metadata.
128
     *
129
     * @var MetadataCollection
130
     */
131
    private $metadata;
132
133
    /** @var array<string, bool> */
134
    private $nonAnnotationClasses = [];
135
136
    /**
137
     * Hash-map for handle types declaration.
138
     *
139
     * @var array
140
     */
141
    private static $typeMap = [
142
        'float'     => 'double',
143
        'bool'      => 'boolean',
144
        // allow uppercase Boolean in honor of George Boole
145
        'Boolean'   => 'boolean',
146
        'int'       => 'integer',
147
    ];
148
149
    /**
150
     * Constructs a new DocParser.
151
     */
152 294
    public function __construct()
153
    {
154 294
        $this->lexer    = new DocLexer;
155 294
        $this->metadata = InternalAnnotations::createMetadata();
156 294
    }
157
158
    /**
159
     * Sets the annotation names that are ignored during the parsing process.
160
     *
161
     * The names are supposed to be the raw names as used in the class, not the
162
     * fully qualified class names.
163
     *
164
     * @param bool[] $names indexed by annotation name
165
     *
166
     * @return void
167
     */
168 49
    public function setIgnoredAnnotationNames(array $names)
169
    {
170 49
        $this->ignoredAnnotationNames = $names;
171 49
    }
172
173
    /**
174
     * Sets the annotation namespaces that are ignored during the parsing process.
175
     *
176
     * @param bool[] $ignoredAnnotationNamespaces indexed by annotation namespace name
177
     *
178
     * @return void
179
     */
180 60
    public function setIgnoredAnnotationNamespaces($ignoredAnnotationNamespaces)
181
    {
182 60
        $this->ignoredAnnotationNamespaces = $ignoredAnnotationNamespaces;
183 60
    }
184
185
    /**
186
     * Sets ignore on not-imported annotations.
187
     *
188
     * @param boolean $bool
189
     *
190
     * @return void
191
     */
192 274
    public function setIgnoreNotImportedAnnotations($bool)
193
    {
194 274
        $this->ignoreNotImportedAnnotations = (boolean) $bool;
195 274
    }
196
197
    /**
198
     * Sets the default namespaces.
199
     *
200
     * @param string $namespace
201
     *
202
     * @return void
203
     *
204
     * @throws \RuntimeException
205
     */
206 2
    public function addNamespace($namespace)
207
    {
208 2
        if ($this->imports) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->imports of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
209
            throw new \RuntimeException('You must either use addNamespace(), or setImports(), but not both.');
210
        }
211
212 2
        $this->namespaces[] = $namespace;
213 2
    }
214
215
    /**
216
     * Sets the imports.
217
     *
218
     * @param array $imports
219
     *
220
     * @return void
221
     *
222
     * @throws \RuntimeException
223
     */
224 273
    public function setImports(array $imports)
225
    {
226 273
        if ($this->namespaces) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->namespaces of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
227
            throw new \RuntimeException('You must either use addNamespace(), or setImports(), but not both.');
228
        }
229
230 273
        $this->imports = $imports;
231 273
    }
232
233
    /**
234
     * Sets current target context as bitmask.
235
     *
236
     * @param integer $target
237
     *
238
     * @return void
239
     */
240 274
    public function setTarget($target)
241
    {
242 274
        $this->target = $target;
243 274
    }
244
245
    /**
246
     * Parses the given docblock string for annotations.
247
     *
248
     * @param string $input   The docblock string to parse.
249
     * @param string $context The parsing context.
250
     *
251
     * @return array Array of annotations. If no annotations are found, an empty array is returned.
252
     */
253 294
    public function parse($input, $context = '')
254
    {
255 294
        $pos = $this->findInitialTokenPosition($input);
256 294
        if ($pos === null) {
257 19
            return [];
258
        }
259
260 293
        $this->context = $context;
261
262 293
        $this->lexer->setInput(trim(substr($input, $pos), '* /'));
263 293
        $this->lexer->moveNext();
264
265 293
        return $this->Annotations();
266
    }
267
268
    /**
269
     * Finds the first valid annotation
270
     *
271
     * @param string $input The docblock string to parse
272
     *
273
     * @return int|null
274
     */
275 294
    private function findInitialTokenPosition($input)
276
    {
277 294
        $pos = 0;
278
279
        // search for first valid annotation
280 294
        while (($pos = strpos($input, '@', $pos)) !== false) {
281 294
            $preceding = substr($input, $pos - 1, 1);
282
283
            // if the @ is preceded by a space, a tab or * it is valid
284 294
            if ($pos === 0 || $preceding === ' ' || $preceding === '*' || $preceding === "\t") {
285 293
                return $pos;
286
            }
287
288 2
            $pos++;
289
        }
290
291 19
        return null;
292
    }
293
294
    /**
295
     * Attempts to match the given token with the current lookahead token.
296
     * If they match, updates the lookahead token; otherwise raises a syntax error.
297
     *
298
     * @param integer $token Type of token.
299
     *
300
     * @return boolean True if tokens match; false otherwise.
301
     */
302 293
    private function match($token)
303
    {
304 293
        if ( ! $this->lexer->isNextToken($token) ) {
305 1
            $this->syntaxError($this->lexer->getLiteral($token));
306
        }
307
308 293
        return $this->lexer->moveNext();
309
    }
310
311
    /**
312
     * Attempts to match the current lookahead token with any of the given tokens.
313
     *
314
     * If any of them matches, this method updates the lookahead token; otherwise
315
     * a syntax error is raised.
316
     *
317
     * @param array $tokens
318
     *
319
     * @return boolean
320
     */
321 14
    private function matchAny(array $tokens)
322
    {
323 14
        if ( ! $this->lexer->isNextTokenAny($tokens)) {
324 1
            $this->syntaxError(implode(' or ', array_map([$this->lexer, 'getLiteral'], $tokens)));
325
        }
326
327 13
        return $this->lexer->moveNext();
328
    }
329
330
    /**
331
     * Generates a new syntax error.
332
     *
333
     * @param string     $expected Expected string.
334
     * @param array|null $token    Optional token.
335
     *
336
     * @return void
337
     *
338
     * @throws AnnotationException
339
     */
340 12
    private function syntaxError($expected, $token = null)
341
    {
342 12
        if ($token === null) {
343 12
            $token = $this->lexer->lookahead;
344
        }
345
346 12
        $message  = sprintf('Expected %s, got ', $expected);
347 12
        $message .= ($this->lexer->lookahead === null)
348
            ? 'end of string'
349 12
            : sprintf("'%s' at position %s", $token['value'], $token['position']);
350
351 12
        if (strlen($this->context)) {
352 9
            $message .= ' in ' . $this->context;
353
        }
354
355 12
        $message .= '.';
356
357 12
        throw AnnotationException::syntaxError($message);
358
    }
359
360
    /**
361
     * Attempts to check if a class exists or not. This always uses PHP autoloading mechanism.
362
     *
363
     * @param string $fqcn
364
     *
365
     * @return boolean
366
     */
367 286
    private function classExists($fqcn)
368
    {
369 286
        if (isset($this->classExists[$fqcn])) {
370 241
            return $this->classExists[$fqcn];
371
        }
372
373
        // final check, does this class exist?
374 286
        return $this->classExists[$fqcn] = class_exists($fqcn);
375
    }
376
377
    /**
378
     * Collects parsing metadata for a given annotation class
379
     *
380
     * @param string $name The annotation name
381
     *
382
     * @return void
383
     */
384 265
    private function collectAnnotationMetadata($name)
385
    {
386 265
        if (self::$metadataParser === null) {
387 1
            self::$metadataParser = new self();
388
389 1
            self::$metadataParser->setIgnoreNotImportedAnnotations(true);
390 1
            self::$metadataParser->setIgnoredAnnotationNames($this->ignoredAnnotationNames);
391 1
            self::$metadataParser->setImports([
392 1
                'enum'          => 'Doctrine\Annotations\Annotation\Enum',
393
                'target'        => 'Doctrine\Annotations\Annotation\Target',
394
                'attribute'     => 'Doctrine\Annotations\Annotation\Attribute',
395
                'attributes'    => 'Doctrine\Annotations\Annotation\Attributes'
396
            ]);
397
        }
398
399 265
        $class      = new ReflectionClass($name);
400 265
        $docComment = $class->getDocComment();
401
402
        // verify that the class is really meant to be an annotation
403 265
        if (strpos($docComment, '@Annotation') === false) {
404 4
            $this->nonAnnotationClasses[$name] = true;
405 4
            return;
406
        }
407
408 261
        $constructor       = $class->getConstructor();
409 261
        $useConstructor    = $constructor !== null && $constructor->getNumberOfParameters() > 0;
410 261
        $annotationBuilder = new AnnotationMetadataBuilder($name);
411
412 261
        if ($useConstructor) {
413 89
            $annotationBuilder->withUsingConstructor();
414
        }
415
416 261
        self::$metadataParser->setTarget(Target::TARGET_CLASS);
417
418 261
        foreach (self::$metadataParser->parse($docComment, 'class @' . $name) as $annotation) {
419 203
            if ($annotation instanceof Target) {
420 203
                $annotationBuilder->withTarget(AnnotationTarget::fromAnnotation($annotation));
421
422 203
                continue;
423
            }
424
425 84
            if ($annotation instanceof Attributes) {
426 84
                foreach ($annotation->value as $attribute) {
427 84
                    $propertyBuilder = new PropertyMetadataBuilder($attribute->name);
428
429 84
                    $this->collectAttributeTypeMetadata($propertyBuilder, $attribute);
430 84
                    $annotationBuilder->withProperty($propertyBuilder->build());
431
                }
432
            }
433
        }
434
435 255
        if ($useConstructor) {
436 89
            $this->metadata->add($annotationBuilder->build());
437
438 89
            return;
439
        }
440
441
        // if there is no constructor we will inject values into public properties
442
443
        // collect all public properties
444 184
        foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $i => $property) {
445 169
            $propertyBuilder = new PropertyMetadataBuilder($property->getName());
446 169
            $propertyComment = $property->getDocComment();
447
448 169
            if ($i === 0) {
449 169
                $propertyBuilder->withBeingDefault();
450
            }
451
452
453 169
            if ($propertyComment === false) {
454 74
                $annotationBuilder->withProperty($propertyBuilder->build());
455
456 74
                continue;
457
            }
458
459 114
            $attribute           = new Attribute();
460 114
            $attribute->required = (false !== strpos($propertyComment, '@Required'));
0 ignored issues
show
Bug introduced by
It seems like $propertyComment can also be of type true; however, parameter $haystack of strpos() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

460
            $attribute->required = (false !== strpos(/** @scrutinizer ignore-type */ $propertyComment, '@Required'));
Loading history...
461 114
            $attribute->name     = $property->name;
462 114
            $attribute->type     = (false !== strpos($propertyComment, '@var') && preg_match('/@var\s+([^\s]+)/',$propertyComment, $matches))
0 ignored issues
show
Bug introduced by
It seems like $propertyComment can also be of type true; however, parameter $subject of preg_match() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

462
            $attribute->type     = (false !== strpos($propertyComment, '@var') && preg_match('/@var\s+([^\s]+)/',/** @scrutinizer ignore-type */ $propertyComment, $matches))
Loading history...
463 114
                ? $matches[1]
464
                : 'mixed';
465
466 114
            $this->collectAttributeTypeMetadata($propertyBuilder, $attribute);
467
468
            // checks if the property has @Enum
469 114
            if (false !== strpos($propertyComment, '@Enum')) {
470 5
                $context = 'property ' . $class->name . "::\$" . $property->name;
471
472 5
                self::$metadataParser->setTarget(Target::TARGET_PROPERTY);
473
474 5
                foreach (self::$metadataParser->parse($propertyComment, $context) as $annotation) {
0 ignored issues
show
Bug introduced by
It seems like $propertyComment can also be of type true; however, parameter $input of Doctrine\Annotations\DocParser::parse() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

474
                foreach (self::$metadataParser->parse(/** @scrutinizer ignore-type */ $propertyComment, $context) as $annotation) {
Loading history...
475 3
                    if ( ! $annotation instanceof Enum) {
476
                        continue;
477
                    }
478
479 3
                    $propertyBuilder = $propertyBuilder->withEnum([
480 3
                        'value'   => $annotation->value,
481 3
                        'literal' => ( ! empty($annotation->literal))
482 1
                            ? $annotation->literal
483 3
                            : $annotation->value,
484
                    ]);
485
                }
486
            }
487
488 112
            $annotationBuilder->withProperty($propertyBuilder->build());
489
        }
490
491 182
        $this->metadata->add($annotationBuilder->build());
492 182
    }
493
494
    /**
495
     * Collects parsing metadata for a given attribute.
496
     *
497
     * @param array     $metadata
498
     * @param Attribute $attribute
499
     */
500 198
    private function collectAttributeTypeMetadata(
501
        PropertyMetadataBuilder $metadata,
502
        Attribute $attribute
503
    ) : void {
504
        // handle internal type declaration
505 198
        $type = self::$typeMap[$attribute->type] ?? $attribute->type;
506
507
        // handle the case if the property type is mixed
508 198
        if ('mixed' === $type) {
509 193
            return;
510
        }
511
512 174
        if ($attribute->required) {
513 4
            $metadata->withBeingRequired();
514
        }
515
516
        // Evaluate type
517
518
        // Checks if the property has array<type>
519 174
        if (false !== $pos = strpos($type, '<')) {
520 169
            $arrayType = substr($type, $pos + 1, -1);
521
522 169
            $metadata->withType([
523 169
                'type' => 'array',
524 169
                'array_type' => self::$typeMap[$arrayType] ?? $arrayType,
525
            ]);
526
527 169
            return;
528
        }
529
530
        // Checks if the property has type[]
531 174
         if (false !== $pos = strrpos($type, '[')) {
532 169
            $arrayType = substr($type, 0, $pos);
533
534 169
            $metadata->withType([
535 169
                'type'            => 'array',
536 169
                'array_type' => self::$typeMap[$arrayType] ?? $arrayType,
537
            ]);
538
539 169
            return;
540
        }
541
542 174
        $metadata->withType([
543 174
            'type'  => $type,
544 174
            'value' => $attribute->type,
545
        ]);
546 174
    }
547
548
    /**
549
     * Annotations ::= Annotation {[ "*" ]* [Annotation]}*
550
     *
551
     * @return array
552
     */
553 293
    private function Annotations()
554
    {
555 293
        $annotations = [];
556
557 293
        while (null !== $this->lexer->lookahead) {
558 293
            if (DocLexer::T_AT !== $this->lexer->lookahead['type']) {
559 37
                $this->lexer->moveNext();
560 37
                continue;
561
            }
562
563
            // make sure the @ is preceded by non-catchable pattern
564 293
            if (null !== $this->lexer->token && $this->lexer->lookahead['position'] === $this->lexer->token['position'] + strlen($this->lexer->token['value'])) {
565 8
                $this->lexer->moveNext();
566 8
                continue;
567
            }
568
569
            // make sure the @ is followed by either a namespace separator, or
570
            // an identifier token
571 293
            if ((null === $peek = $this->lexer->glimpse())
572 293
                || (DocLexer::T_NAMESPACE_SEPARATOR !== $peek['type'] && !in_array($peek['type'], self::$classIdentifiers, true))
573 293
                || $peek['position'] !== $this->lexer->lookahead['position'] + 1) {
574 1
                $this->lexer->moveNext();
575 1
                continue;
576
            }
577
578 293
            $this->isNestedAnnotation = false;
579 293
            if (false !== $annot = $this->Annotation()) {
580 244
                $annotations[] = $annot;
581
            }
582
        }
583
584 287
        return $annotations;
585
    }
586
587
    /**
588
     * Annotation     ::= "@" AnnotationName MethodCall
589
     * AnnotationName ::= QualifiedName | SimpleName
590
     * QualifiedName  ::= NameSpacePart "\" {NameSpacePart "\"}* SimpleName
591
     * NameSpacePart  ::= identifier | null | false | true
592
     * SimpleName     ::= identifier | null | false | true
593
     *
594
     * @return mixed False if it is not a valid annotation.
595
     *
596
     * @throws AnnotationException
597
     */
598 293
    private function Annotation()
599
    {
600 293
        $this->match(DocLexer::T_AT);
601
602
        // check if we have an annotation
603 293
        $name = $this->Identifier();
604
605 292
        if ($this->lexer->isNextToken(DocLexer::T_MINUS)
606 292
            && $this->lexer->nextTokenIsAdjacent()
607
        ) {
608
            // Annotations with dashes, such as "@foo-" or "@foo-bar", are to be discarded
609 3
            return false;
610
        }
611
612
        // only process names which are not fully qualified, yet
613
        // fully qualified names must start with a \
614 290
        $originalName = $name;
615
616 290
        if ('\\' !== $name[0]) {
617 288
            $pos = strpos($name, '\\');
618 288
            $alias = (false === $pos)? $name : substr($name, 0, $pos);
619 288
            $found = false;
620 288
            $loweredAlias = strtolower($alias);
621
622 288
            if ($this->namespaces) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->namespaces of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
623 2
                foreach ($this->namespaces as $namespace) {
624 2
                    if ($this->classExists($namespace.'\\'.$name)) {
625 2
                        $name = $namespace.'\\'.$name;
626 2
                        $found = true;
627 2
                        break;
628
                    }
629
                }
630 288
            } elseif (isset($this->imports[$loweredAlias])) {
631 237
                $found = true;
632 237
                $name  = (false !== $pos)
633 1
                    ? $this->imports[$loweredAlias] . substr($name, $pos)
634 237
                    : $this->imports[$loweredAlias];
635 288
            } elseif ( ! isset($this->ignoredAnnotationNames[$name])
636 288
                && isset($this->imports['__NAMESPACE__'])
637 288
                && $this->classExists($this->imports['__NAMESPACE__'] . '\\' . $name)
638
            ) {
639 36
                $name  = $this->imports['__NAMESPACE__'].'\\'.$name;
640 36
                $found = true;
641 288
            } elseif (! isset($this->ignoredAnnotationNames[$name]) && $this->classExists($name)) {
642 182
                $found = true;
643
            }
644
645 288
            if ( ! $found) {
646 288
                if ($this->isIgnoredAnnotation($name)) {
647 286
                    return false;
648
                }
649
650 2
                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));
651
            }
652
        }
653
654 265
        $name = ltrim($name,'\\');
655
656 265
        if ( ! $this->classExists($name)) {
657
            throw AnnotationException::semanticalError(sprintf('The annotation "@%s" in %s does not exist, or could not be auto-loaded.', $name, $this->context));
658
        }
659
660
        // at this point, $name contains the fully qualified class name of the
661
        // annotation, and it is also guaranteed that this class exists, and
662
        // that it is loaded
663
664
665
        // collects the metadata annotation only if there is not yet
666 265
        if (! $this->metadata->has($name) && ! array_key_exists($name, $this->nonAnnotationClasses)) {
667 265
            $this->collectAnnotationMetadata($name);
668
        }
669
670
        // verify that the class is really meant to be an annotation and not just any ordinary class
671 265
        if (array_key_exists($name, $this->nonAnnotationClasses)) {
672 4
            if ($this->ignoreNotImportedAnnotations || isset($this->ignoredAnnotationNames[$originalName])) {
673 2
                return false;
674
            }
675
676 2
            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));
677
        }
678
679
        //if target is nested annotation
680 261
        $target = $this->isNestedAnnotation ? Target::TARGET_ANNOTATION : $this->target;
681
682
        // Next will be nested
683 261
        $this->isNestedAnnotation = true;
684 261
        $metadata                 = $this->metadata->get($name);
685
686
        //if annotation does not support current target
687 261
        if (($metadata->getTarget()->unwrap() & $target) === 0 && $target) {
688 5
            throw AnnotationException::semanticalError(
689 5
                sprintf('Annotation @%s is not allowed to be declared on %s. You may only use this annotation on these code elements: %s.',
690 5
                     $originalName, $this->context, $metadata->getTarget()->describe())
691
            );
692
        }
693
694 261
        $values = $this->MethodCall();
695
696
        // checks all declared attributes for enums
697 249
        foreach ($metadata->getProperties() as $property) {
698 232
            $propertyName = $property->getName();
699 232
            $enum         = $property->getEnum();
700
701
            // checks if the attribute is a valid enumerator
702 232
            if ($enum !== null && isset($values[$propertyName]) && ! in_array($values[$propertyName], $enum['value'])) {
703 3
                throw AnnotationException::enumeratorError($propertyName, $name, $this->context, $enum['literal'], $values[$propertyName]);
704
            }
705
        }
706
707
        // checks all declared attributes
708 249
        foreach ($metadata->getProperties() as $property) {
709 232
            $propertyName = $property->getName();
710 232
            $valueName    = $propertyName;
711 232
            $type         = $property->getType();
712
713 232
            if ($property->isDefault() && !isset($values[$propertyName]) && isset($values['value'])) {
714 90
                $valueName = 'value';
715
            }
716
717
            // handle a not given attribute or null value
718 232
            if (! isset($values[$valueName])) {
719 203
                if ($property->isRequired()) {
720 2
                    throw AnnotationException::requiredError($propertyName, $originalName, $this->context, 'a(n) ' . $type['value']);
721
                }
722
723 203
                continue;
724
            }
725
726 225
            if ($type !== null && $type['type'] === 'array') {
727
                // handle the case of a single value
728 204
                if ( ! is_array($values[$valueName])) {
729 201
                    $values[$valueName] = [$values[$valueName]];
730
                }
731
732
                // checks if the attribute has array type declaration, such as "array<string>"
733 204
                if (isset($type['array_type'])) {
734 204
                    foreach ($values[$valueName] as $item) {
735 204
                        if (gettype($item) !== $type['array_type'] && !$item instanceof $type['array_type']) {
736 36
                            throw AnnotationException::attributeTypeError($propertyName, $originalName, $this->context, 'either a(n) '.$type['array_type'].', or an array of '.$type['array_type'].'s', $item);
737
                        }
738
                    }
739
                }
740 190
            } elseif ($type !== null && gettype($values[$valueName]) !== $type['type'] && !$values[$valueName] instanceof $type['type']) {
741 72
                throw AnnotationException::attributeTypeError($propertyName, $originalName, $this->context, 'a(n) '.$type['value'], $values[$valueName]);
742
            }
743
        }
744
745
        // check if the annotation expects values via the constructor,
746
        // or directly injected into public properties
747 249
        if ($metadata->usesConstructor()) {
748 210
            return new $name($values);
749
        }
750
751 189
        $instance = new $name();
752
753 189
        foreach ($values as $property => $value) {
754 164
            if (! isset($metadata->getProperties()[$property])) {
755 93
                if ('value' !== $property) {
756 1
                    throw AnnotationException::creationError(
757 1
                        sprintf(
758 1
                            'The annotation @%s declared on %s does not have a property named "%s". Available properties: %s',
759 1
                            $originalName,
760 1
                            $this->context,
761 1
                            $property,
762 1
                            implode(', ', array_keys($metadata->getProperties()))
763
                        )
764
                    );
765
                }
766
767 92
                $defaultProperty = $metadata->getDefaultProperty();
768
769
                // handle the case if the property has no annotations
770 92
                if ($defaultProperty === null) {
771 2
                    throw AnnotationException::creationError(sprintf('The annotation @%s declared on %s does not accept any values, but got %s.', $originalName, $this->context, json_encode($values)));
772
                }
773
774 90
                $property = $defaultProperty->getName();
775
            }
776
777 161
            $instance->{$property} = $value;
778
        }
779
780 186
        return $instance;
781
    }
782
783
    /**
784
     * MethodCall ::= ["(" [Values] ")"]
785
     *
786
     * @return array
787
     */
788 261
    private function MethodCall()
789
    {
790 261
        $values = [];
791
792 261
        if ( ! $this->lexer->isNextToken(DocLexer::T_OPEN_PARENTHESIS)) {
793 56
            return $values;
794
        }
795
796 243
        $this->match(DocLexer::T_OPEN_PARENTHESIS);
797
798 243
        if ( ! $this->lexer->isNextToken(DocLexer::T_CLOSE_PARENTHESIS)) {
799 243
            $values = $this->Values();
800
        }
801
802 232
        $this->match(DocLexer::T_CLOSE_PARENTHESIS);
803
804 231
        return $values;
805
    }
806
807
    /**
808
     * Values ::= Array | Value {"," Value}* [","]
809
     *
810
     * @return array
811
     */
812 243
    private function Values()
813
    {
814 243
        $values = [$this->Value()];
815
816 232
        while ($this->lexer->isNextToken(DocLexer::T_COMMA)) {
817 94
            $this->match(DocLexer::T_COMMA);
818
819 94
            if ($this->lexer->isNextToken(DocLexer::T_CLOSE_PARENTHESIS)) {
820 1
                break;
821
            }
822
823 93
            $token = $this->lexer->lookahead;
824 93
            $value = $this->Value();
825
826 93
            if ( ! is_object($value) && ! is_array($value)) {
827
                $this->syntaxError('Value', $token);
828
            }
829
830 93
            $values[] = $value;
831
        }
832
833 232
        foreach ($values as $k => $value) {
834 232
            if (is_object($value) && $value instanceof \stdClass) {
835 194
                $values[$value->name] = $value->value;
836 218
            } else if ( ! isset($values['value'])){
837 218
                $values['value'] = $value;
838
            } else {
839 1
                if ( ! is_array($values['value'])) {
840 1
                    $values['value'] = [$values['value']];
841
                }
842
843 1
                $values['value'][] = $value;
844
            }
845
846 232
            unset($values[$k]);
847
        }
848
849 232
        return $values;
850
    }
851
852
    /**
853
     * Constant ::= integer | string | float | boolean
854
     *
855
     * @return mixed
856
     *
857
     * @throws AnnotationException
858
     */
859 74
    private function Constant()
860
    {
861 74
        $identifier = $this->Identifier();
862
863 74
        if ( ! defined($identifier) && false !== strpos($identifier, '::') && '\\' !== $identifier[0]) {
864 16
            list($className, $const) = explode('::', $identifier);
865
866 16
            $pos = strpos($className, '\\');
867 16
            $alias = (false === $pos) ? $className : substr($className, 0, $pos);
868 16
            $found = false;
869 16
            $loweredAlias = strtolower($alias);
870
871
            switch (true) {
872 16
                case !empty ($this->namespaces):
873
                    foreach ($this->namespaces as $ns) {
874
                        if (class_exists($ns.'\\'.$className) || interface_exists($ns.'\\'.$className)) {
875
                             $className = $ns.'\\'.$className;
876
                             $found = true;
877
                             break;
878
                        }
879
                    }
880
                    break;
881
882 16
                case isset($this->imports[$loweredAlias]):
883 14
                    $found     = true;
884 14
                    $className = (false !== $pos)
885
                        ? $this->imports[$loweredAlias] . substr($className, $pos)
886 14
                        : $this->imports[$loweredAlias];
887 14
                    break;
888
889
                default:
890 2
                    if(isset($this->imports['__NAMESPACE__'])) {
891
                        $ns = $this->imports['__NAMESPACE__'];
892
893
                        if (class_exists($ns.'\\'.$className) || interface_exists($ns.'\\'.$className)) {
894
                            $className = $ns.'\\'.$className;
895
                            $found = true;
896
                        }
897
                    }
898 2
                    break;
899
            }
900
901 16
            if ($found) {
902 14
                 $identifier = $className . '::' . $const;
903
            }
904
        }
905
906
        // checks if identifier ends with ::class, \strlen('::class') === 7
907 74
        $classPos = stripos($identifier, '::class');
908 74
        if ($classPos === strlen($identifier) - 7) {
909 4
            return substr($identifier, 0, $classPos);
910
        }
911
912 70
        if (!defined($identifier)) {
913 1
            throw AnnotationException::semanticalErrorConstants($identifier, $this->context);
914
        }
915
916 69
        return constant($identifier);
917
    }
918
919
    /**
920
     * Identifier ::= string
921
     *
922
     * @return string
923
     */
924 293
    private function Identifier()
925
    {
926
        // check if we have an annotation
927 293
        if ( ! $this->lexer->isNextTokenAny(self::$classIdentifiers)) {
928 8
            $this->syntaxError('namespace separator or identifier');
929
        }
930
931 293
        $this->lexer->moveNext();
932
933 293
        $className = $this->lexer->token['value'];
934
935 293
        while ($this->lexer->lookahead['position'] === ($this->lexer->token['position'] + strlen($this->lexer->token['value']))
936 293
                && $this->lexer->isNextToken(DocLexer::T_NAMESPACE_SEPARATOR)) {
937
938 1
            $this->match(DocLexer::T_NAMESPACE_SEPARATOR);
939 1
            $this->matchAny(self::$classIdentifiers);
940
941
            $className .= '\\' . $this->lexer->token['value'];
942
        }
943
944 292
        return $className;
945
    }
946
947
    /**
948
     * Value ::= PlainValue | FieldAssignment
949
     *
950
     * @return mixed
951
     */
952 243
    private function Value()
953
    {
954 243
        $peek = $this->lexer->glimpse();
955
956 243
        if (DocLexer::T_EQUALS === $peek['type']) {
957 196
            return $this->FieldAssignment();
958
        }
959
960 228
        return $this->PlainValue();
961
    }
962
963
    /**
964
     * PlainValue ::= integer | string | float | boolean | Array | Annotation
965
     *
966
     * @return mixed
967
     */
968 243
    private function PlainValue()
969
    {
970 243
        if ($this->lexer->isNextToken(DocLexer::T_OPEN_CURLY_BRACES)) {
971 138
            return $this->Arrayx();
972
        }
973
974 242
        if ($this->lexer->isNextToken(DocLexer::T_AT)) {
975 114
            return $this->Annotation();
976
        }
977
978 233
        if ($this->lexer->isNextToken(DocLexer::T_IDENTIFIER)) {
979 74
            return $this->Constant();
980
        }
981
982 232
        switch ($this->lexer->lookahead['type']) {
983 232
            case DocLexer::T_STRING:
984 225
                $this->match(DocLexer::T_STRING);
985 225
                return $this->lexer->token['value'];
986
987 81
            case DocLexer::T_INTEGER:
988 53
                $this->match(DocLexer::T_INTEGER);
989 53
                return (int)$this->lexer->token['value'];
990
991 30
            case DocLexer::T_FLOAT:
992 28
                $this->match(DocLexer::T_FLOAT);
993 28
                return (float)$this->lexer->token['value'];
994
995 2
            case DocLexer::T_TRUE:
996
                $this->match(DocLexer::T_TRUE);
997
                return true;
998
999 2
            case DocLexer::T_FALSE:
1000
                $this->match(DocLexer::T_FALSE);
1001
                return false;
1002
1003 2
            case DocLexer::T_NULL:
1004
                $this->match(DocLexer::T_NULL);
1005
                return null;
1006
1007
            default:
1008 2
                $this->syntaxError('PlainValue');
1009
        }
1010
    }
1011
1012
    /**
1013
     * FieldAssignment ::= FieldName "=" PlainValue
1014
     * FieldName ::= identifier
1015
     *
1016
     * @return \stdClass
1017
     */
1018 196
    private function FieldAssignment()
1019
    {
1020 196
        $this->match(DocLexer::T_IDENTIFIER);
1021 196
        $fieldName = $this->lexer->token['value'];
1022
1023 196
        $this->match(DocLexer::T_EQUALS);
1024
1025 196
        $item = new \stdClass();
1026 196
        $item->name  = $fieldName;
1027 196
        $item->value = $this->PlainValue();
1028
1029 194
        return $item;
1030
    }
1031
1032
    /**
1033
     * Array ::= "{" ArrayEntry {"," ArrayEntry}* [","] "}"
1034
     *
1035
     * @return array
1036
     */
1037 138
    private function Arrayx()
1038
    {
1039 138
        $array = $values = [];
1040
1041 138
        $this->match(DocLexer::T_OPEN_CURLY_BRACES);
1042
1043
        // If the array is empty, stop parsing and return.
1044 138
        if ($this->lexer->isNextToken(DocLexer::T_CLOSE_CURLY_BRACES)) {
1045 1
            $this->match(DocLexer::T_CLOSE_CURLY_BRACES);
1046
1047 1
            return $array;
1048
        }
1049
1050 138
        $values[] = $this->ArrayEntry();
1051
1052 138
        while ($this->lexer->isNextToken(DocLexer::T_COMMA)) {
1053 119
            $this->match(DocLexer::T_COMMA);
1054
1055
            // optional trailing comma
1056 119
            if ($this->lexer->isNextToken(DocLexer::T_CLOSE_CURLY_BRACES)) {
1057 86
                break;
1058
            }
1059
1060 119
            $values[] = $this->ArrayEntry();
1061
        }
1062
1063 138
        $this->match(DocLexer::T_CLOSE_CURLY_BRACES);
1064
1065 138
        foreach ($values as $value) {
1066 138
            list ($key, $val) = $value;
1067
1068 138
            if ($key !== null) {
1069 13
                $array[$key] = $val;
1070
            } else {
1071 129
                $array[] = $val;
1072
            }
1073
        }
1074
1075 138
        return $array;
1076
    }
1077
1078
    /**
1079
     * ArrayEntry ::= Value | KeyValuePair
1080
     * KeyValuePair ::= Key ("=" | ":") PlainValue | Constant
1081
     * Key ::= string | integer | Constant
1082
     *
1083
     * @return array
1084
     */
1085 138
    private function ArrayEntry()
1086
    {
1087 138
        $peek = $this->lexer->glimpse();
1088
1089 138
        if (DocLexer::T_EQUALS === $peek['type']
1090 138
                || DocLexer::T_COLON === $peek['type']) {
1091
1092 13
            if ($this->lexer->isNextToken(DocLexer::T_IDENTIFIER)) {
1093 5
                $key = $this->Constant();
1094
            } else {
1095 8
                $this->matchAny([DocLexer::T_INTEGER, DocLexer::T_STRING]);
1096 8
                $key = $this->lexer->token['value'];
1097
            }
1098
1099 13
            $this->matchAny([DocLexer::T_EQUALS, DocLexer::T_COLON]);
1100
1101 13
            return [$key, $this->PlainValue()];
1102
        }
1103
1104 129
        return [null, $this->Value()];
1105
    }
1106
1107
    /**
1108
     * Checks whether the given $name matches any ignored annotation name or namespace
1109
     *
1110
     * @param string $name
1111
     *
1112
     * @return bool
1113
     */
1114 288
    private function isIgnoredAnnotation($name)
1115
    {
1116 288
        if ($this->ignoreNotImportedAnnotations || isset($this->ignoredAnnotationNames[$name])) {
1117 272
            return true;
1118
        }
1119
1120 17
        foreach (array_keys($this->ignoredAnnotationNamespaces) as $ignoredAnnotationNamespace) {
1121 15
            $ignoredAnnotationNamespace = rtrim($ignoredAnnotationNamespace, '\\') . '\\';
1122
1123 15
            if (0 === stripos(rtrim($name, '\\') . '\\', $ignoredAnnotationNamespace)) {
1124 15
                return true;
1125
            }
1126
        }
1127
1128 2
        return false;
1129
    }
1130
}
1131