Failed Conditions
Pull Request — master (#247)
by Michael
05:36
created

DocParser   F

Complexity

Total Complexity 172

Size/Duplication

Total Lines 1081
Duplicated Lines 0 %

Test Coverage

Coverage 93.3%

Importance

Changes 0
Metric Value
wmc 172
eloc 399
dl 0
loc 1081
ccs 376
cts 403
cp 0.933
rs 2
c 0
b 0
f 0

27 Methods

Rating   Name   Duplication   Size   Complexity  
B Values() 0 38 10
A ArrayEntry() 0 20 4
D collectAnnotationMetadata() 0 102 19
A setImports() 0 7 2
A MethodCall() 0 17 3
A setTarget() 0 3 1
A setIgnoreNotImportedAnnotations() 0 3 1
A match() 0 7 2
A setIgnoredAnnotationNames() 0 3 1
A setIgnoredAnnotationNamespaces() 0 3 1
A parse() 0 13 2
A syntaxError() 0 18 4
A collectAttributeTypeMetadata() 0 42 5
B PlainValue() 0 41 10
A addNamespace() 0 7 2
A __construct() 0 4 1
A isIgnoredAnnotation() 0 15 5
A matchAny() 0 7 2
A classExists() 0 8 2
A Identifier() 0 21 4
B Annotations() 0 32 10
A findInitialTokenPosition() 0 17 6
A Arrayx() 0 39 6
F Annotation() 0 175 49
C Constant() 0 58 17
A FieldAssignment() 0 12 1
A Value() 0 9 2

How to fix   Complexity   

Complex Class

Complex classes like DocParser often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use DocParser, and based on these observations, apply Extract Interface, too.

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 290
    public function __construct()
153
    {
154 290
        $this->lexer    = new DocLexer;
155 290
        $this->metadata = InternalAnnotations::createMetadata();
156 290
    }
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 47
    public function setIgnoredAnnotationNames(array $names)
169
    {
170 47
        $this->ignoredAnnotationNames = $names;
171 47
    }
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 58
    public function setIgnoredAnnotationNamespaces($ignoredAnnotationNamespaces)
181
    {
182 58
        $this->ignoredAnnotationNamespaces = $ignoredAnnotationNamespaces;
183 58
    }
184
185
    /**
186
     * Sets ignore on not-imported annotations.
187
     *
188
     * @param boolean $bool
189
     *
190
     * @return void
191
     */
192 270
    public function setIgnoreNotImportedAnnotations($bool)
193
    {
194 270
        $this->ignoreNotImportedAnnotations = (boolean) $bool;
195 270
    }
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 269
    public function setImports(array $imports)
225
    {
226 269
        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 269
        $this->imports = $imports;
231 269
    }
232
233
    /**
234
     * Sets current target context as bitmask.
235
     *
236
     * @param integer $target
237
     *
238
     * @return void
239
     */
240 271
    public function setTarget($target)
241
    {
242 271
        $this->target = $target;
243 271
    }
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 290
    public function parse($input, $context = '')
254
    {
255 290
        $pos = $this->findInitialTokenPosition($input);
256 290
        if ($pos === null) {
257 19
            return [];
258
        }
259
260 289
        $this->context = $context;
261
262 289
        $this->lexer->setInput(trim(substr($input, $pos), '* /'));
263 289
        $this->lexer->moveNext();
264
265 289
        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 290
    private function findInitialTokenPosition($input)
276
    {
277 290
        $pos = 0;
278
279
        // search for first valid annotation
280 290
        while (($pos = strpos($input, '@', $pos)) !== false) {
281 290
            $preceding = substr($input, $pos - 1, 1);
282
283
            // if the @ is preceded by a space, a tab or * it is valid
284 290
            if ($pos === 0 || $preceding === ' ' || $preceding === '*' || $preceding === "\t") {
285 289
                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 289
    private function match($token)
303
    {
304 289
        if ( ! $this->lexer->isNextToken($token) ) {
305
            $this->syntaxError($this->lexer->getLiteral($token));
306
        }
307
308 289
        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 11
    private function syntaxError($expected, $token = null)
341
    {
342 11
        if ($token === null) {
343 11
            $token = $this->lexer->lookahead;
344
        }
345
346 11
        $message  = sprintf('Expected %s, got ', $expected);
347 11
        $message .= ($this->lexer->lookahead === null)
348
            ? 'end of string'
349 11
            : sprintf("'%s' at position %s", $token['value'], $token['position']);
350
351 11
        if (strlen($this->context)) {
352 8
            $message .= ' in ' . $this->context;
353
        }
354
355 11
        $message .= '.';
356
357 11
        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 284
    private function classExists($fqcn)
368
    {
369 284
        if (isset($this->classExists[$fqcn])) {
370 240
            return $this->classExists[$fqcn];
371
        }
372
373
        // final check, does this class exist?
374 284
        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 263
    private function collectAnnotationMetadata($name)
385
    {
386 263
        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 263
        $class          = new \ReflectionClass($name);
400 263
        $docComment     = $class->getDocComment();
401 263
        $constructor    = $class->getConstructor();
402 263
        $useConstructor = $constructor !== null && $constructor->getNumberOfParameters() > 0;
403
404
        // verify that the class is really meant to be an annotation
405 263
        if (strpos($docComment, '@Annotation') === false) {
406 4
            $this->nonAnnotationClasses[$name] = true;
407 4
            return;
408
        }
409
410 259
        $annotationBuilder = new AnnotationMetadataBuilder($name);
411
412 259
        if ($useConstructor) {
413 89
            $annotationBuilder = $annotationBuilder->withUsingConstructor();
414
        }
415
416 259
        self::$metadataParser->setTarget(Target::TARGET_CLASS);
417
418 259
        foreach (self::$metadataParser->parse($docComment, 'class @' . $name) as $annotation) {
419 203
            if ($annotation instanceof Target) {
420 203
                $annotationBuilder = $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
                    $annotationBuilder = $annotationBuilder->withProperty(
428 84
                        $this->collectAttributeTypeMetadata(new PropertyMetadataBuilder($attribute->name), $attribute)->build()
429
                    );
430
                }
431
            }
432
        }
433
434
        // if there is no constructor we will inject values into public properties
435 253
        if (! $useConstructor) {
436
            // collect all public properties
437 182
            foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $i => $property) {
438 168
                $propertyBuilder = new PropertyMetadataBuilder($property->getName());
439 168
                $propertyComment = $property->getDocComment();
440
441 168
                if ($i === 0) {
442 168
                    $propertyBuilder = $propertyBuilder->withBeingDefault();
443
                }
444
445
446 168
                if ($propertyComment === false) {
447 73
                    $annotationBuilder = $annotationBuilder->withProperty($propertyBuilder->build());
448
449 73
                    continue;
450
                }
451
452 113
                $attribute           = new Attribute();
453 113
                $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

453
                $attribute->required = (false !== strpos(/** @scrutinizer ignore-type */ $propertyComment, '@Required'));
Loading history...
454 113
                $attribute->name     = $property->name;
455 113
                $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

455
                $attribute->type     = (false !== strpos($propertyComment, '@var') && preg_match('/@var\s+([^\s]+)/',/** @scrutinizer ignore-type */ $propertyComment, $matches))
Loading history...
456 113
                    ? $matches[1]
457
                    : 'mixed';
458
459 113
                $propertyBuilder = $this->collectAttributeTypeMetadata($propertyBuilder, $attribute);
460
461
                // checks if the property has @Enum
462 113
                if (false !== strpos($propertyComment, '@Enum')) {
463 5
                    $context = 'property ' . $class->name . "::\$" . $property->name;
464
465 5
                    self::$metadataParser->setTarget(Target::TARGET_PROPERTY);
466
467 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

467
                    foreach (self::$metadataParser->parse(/** @scrutinizer ignore-type */ $propertyComment, $context) as $annotation) {
Loading history...
468 3
                        if ( ! $annotation instanceof Enum) {
469
                            continue;
470
                        }
471
472 3
                        $propertyBuilder = $propertyBuilder->withEnum([
473 3
                            'value'   => $annotation->value,
474 3
                            'literal' => ( ! empty($annotation->literal))
475 1
                                ? $annotation->literal
476 3
                                : $annotation->value,
477
                        ]);
478
                    }
479
                }
480
481 111
                $annotationBuilder = $annotationBuilder->withProperty($propertyBuilder->build());
482
            }
483
        }
484
485 251
        $this->metadata->add($annotationBuilder->build());
486 251
    }
487
488
    /**
489
     * Collects parsing metadata for a given attribute.
490
     *
491
     * @param array     $metadata
492
     * @param Attribute $attribute
493
     */
494 197
    private function collectAttributeTypeMetadata(
495
        PropertyMetadataBuilder $metadata,
496
        Attribute $attribute
497
    ) : PropertyMetadataBuilder
498
    {
499
        // handle internal type declaration
500 197
        $type = self::$typeMap[$attribute->type] ?? $attribute->type;
501
502
        // handle the case if the property type is mixed
503 197
        if ('mixed' === $type) {
504 193
            return $metadata;
505
        }
506
507 173
        if ($attribute->required) {
508 3
            $metadata = $metadata->withBeingRequired();
509
        }
510
511
        // Evaluate type
512
513
        // Checks if the property has array<type>
514 173
        if (false !== $pos = strpos($type, '<')) {
515 169
            $arrayType = substr($type, $pos + 1, -1);
516
517 169
            return $metadata->withType([
518 169
                'type' => 'array',
519 169
                'array_type' => self::$typeMap[$arrayType] ?? $arrayType,
520
            ]);
521
        }
522
523
        // Checks if the property has type[]
524 173
         if (false !== $pos = strrpos($type, '[')) {
525 169
            $arrayType = substr($type, 0, $pos);
526
527 169
            return $metadata->withType([
528 169
                'type'            => 'array',
529 169
                'array_type' => self::$typeMap[$arrayType] ?? $arrayType,
530
            ]);
531
        }
532
533 173
        return $metadata->withType([
534 173
            'type'  => $type,
535 173
            'value' => $attribute->type,
536
        ]);
537
    }
538
539
    /**
540
     * Annotations ::= Annotation {[ "*" ]* [Annotation]}*
541
     *
542
     * @return array
543
     */
544 289
    private function Annotations()
545
    {
546 289
        $annotations = [];
547
548 289
        while (null !== $this->lexer->lookahead) {
549 289
            if (DocLexer::T_AT !== $this->lexer->lookahead['type']) {
550 33
                $this->lexer->moveNext();
551 33
                continue;
552
            }
553
554
            // make sure the @ is preceded by non-catchable pattern
555 289
            if (null !== $this->lexer->token && $this->lexer->lookahead['position'] === $this->lexer->token['position'] + strlen($this->lexer->token['value'])) {
556 7
                $this->lexer->moveNext();
557 7
                continue;
558
            }
559
560
            // make sure the @ is followed by either a namespace separator, or
561
            // an identifier token
562 289
            if ((null === $peek = $this->lexer->glimpse())
563 289
                || (DocLexer::T_NAMESPACE_SEPARATOR !== $peek['type'] && !in_array($peek['type'], self::$classIdentifiers, true))
564 289
                || $peek['position'] !== $this->lexer->lookahead['position'] + 1) {
565 1
                $this->lexer->moveNext();
566 1
                continue;
567
            }
568
569 289
            $this->isNestedAnnotation = false;
570 289
            if (false !== $annot = $this->Annotation()) {
571 243
                $annotations[] = $annot;
572
            }
573
        }
574
575 283
        return $annotations;
576
    }
577
578
    /**
579
     * Annotation     ::= "@" AnnotationName MethodCall
580
     * AnnotationName ::= QualifiedName | SimpleName
581
     * QualifiedName  ::= NameSpacePart "\" {NameSpacePart "\"}* SimpleName
582
     * NameSpacePart  ::= identifier | null | false | true
583
     * SimpleName     ::= identifier | null | false | true
584
     *
585
     * @return mixed False if it is not a valid annotation.
586
     *
587
     * @throws AnnotationException
588
     */
589 289
    private function Annotation()
590
    {
591 289
        $this->match(DocLexer::T_AT);
592
593
        // check if we have an annotation
594 289
        $name = $this->Identifier();
595
596
        // only process names which are not fully qualified, yet
597
        // fully qualified names must start with a \
598 288
        $originalName = $name;
599
600 288
        if ('\\' !== $name[0]) {
601 286
            $pos = strpos($name, '\\');
602 286
            $alias = (false === $pos)? $name : substr($name, 0, $pos);
603 286
            $found = false;
604 286
            $loweredAlias = strtolower($alias);
605
606 286
            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...
607 2
                foreach ($this->namespaces as $namespace) {
608 2
                    if ($this->classExists($namespace.'\\'.$name)) {
609 2
                        $name = $namespace.'\\'.$name;
610 2
                        $found = true;
611 2
                        break;
612
                    }
613
                }
614 286
            } elseif (isset($this->imports[$loweredAlias])) {
615 236
                $found = true;
616 236
                $name  = (false !== $pos)
617 1
                    ? $this->imports[$loweredAlias] . substr($name, $pos)
618 236
                    : $this->imports[$loweredAlias];
619 286
            } elseif ( ! isset($this->ignoredAnnotationNames[$name])
620 286
                && isset($this->imports['__NAMESPACE__'])
621 286
                && $this->classExists($this->imports['__NAMESPACE__'] . '\\' . $name)
622
            ) {
623 35
                $name  = $this->imports['__NAMESPACE__'].'\\'.$name;
624 35
                $found = true;
625 286
            } elseif (! isset($this->ignoredAnnotationNames[$name]) && $this->classExists($name)) {
626 182
                $found = true;
627
            }
628
629 286
            if ( ! $found) {
630 286
                if ($this->isIgnoredAnnotation($name)) {
631 284
                    return false;
632
                }
633
634 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));
635
            }
636
        }
637
638 263
        $name = ltrim($name,'\\');
639
640 263
        if ( ! $this->classExists($name)) {
641
            throw AnnotationException::semanticalError(sprintf('The annotation "@%s" in %s does not exist, or could not be auto-loaded.', $name, $this->context));
642
        }
643
644
        // at this point, $name contains the fully qualified class name of the
645
        // annotation, and it is also guaranteed that this class exists, and
646
        // that it is loaded
647
648
649
        // collects the metadata annotation only if there is not yet
650 263
        if (! $this->metadata->has($name) && ! array_key_exists($name, $this->nonAnnotationClasses)) {
651 263
            $this->collectAnnotationMetadata($name);
652
        }
653
654
        // verify that the class is really meant to be an annotation and not just any ordinary class
655 263
        if (array_key_exists($name, $this->nonAnnotationClasses)) {
656 4
            if ($this->ignoreNotImportedAnnotations || isset($this->ignoredAnnotationNames[$originalName])) {
657 2
                return false;
658
            }
659
660 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));
661
        }
662
663
        //if target is nested annotation
664 259
        $target = $this->isNestedAnnotation ? Target::TARGET_ANNOTATION : $this->target;
665
666
        // Next will be nested
667 259
        $this->isNestedAnnotation = true;
668
669
        //if annotation does not support current target
670 259
        if (($this->metadata->get($name)->getTarget()->unwrap() & $target) === 0 && $target) {
671 5
            throw AnnotationException::semanticalError(
672 5
                sprintf('Annotation @%s is not allowed to be declared on %s. You may only use this annotation on these code elements: %s.',
673 5
                     $originalName, $this->context, $this->metadata->get($name)->getTarget()->describe())
674
            );
675
        }
676
677 259
        $values = $this->MethodCall();
678
679
        // checks all declared attributes for enums
680 248
        foreach ($this->metadata->get($name)->getProperties() as $property) {
681 232
            $propertyName = $property->getName();
682 232
            $enum         = $property->getEnum();
683
684
            // checks if the attribute is a valid enumerator
685 232
            if ($enum !== null && isset($values[$propertyName]) && ! in_array($values[$propertyName], $enum['value'])) {
686 3
                throw AnnotationException::enumeratorError($propertyName, $name, $this->context, $enum['literal'], $values[$propertyName]);
687
            }
688
        }
689
690
        // checks all declared attributes
691 248
        foreach ($this->metadata->get($name)->getProperties() as $property) {
692 232
            $propertyName = $property->getName();
693 232
            $valueName    = $propertyName;
694 232
            $type         = $property->getType();
695
696 232
            if ($property->isDefault() && !isset($values[$propertyName]) && isset($values['value'])) {
697 90
                $valueName = 'value';
698
            }
699
700
            // handle a not given attribute or null value
701 232
            if (! isset($values[$valueName])) {
702 203
                if ($property->isRequired()) {
703 2
                    throw AnnotationException::requiredError($propertyName, $originalName, $this->context, 'a(n) ' . $type['value']);
704
                }
705
706 203
                continue;
707
            }
708
709 225
            if ($type !== null && $type['type'] === 'array') {
710
                // handle the case of a single value
711 204
                if ( ! is_array($values[$valueName])) {
712 201
                    $values[$valueName] = [$values[$valueName]];
713
                }
714
715
                // checks if the attribute has array type declaration, such as "array<string>"
716 204
                if (isset($type['array_type'])) {
717 204
                    foreach ($values[$valueName] as $item) {
718 204
                        if (gettype($item) !== $type['array_type'] && !$item instanceof $type['array_type']) {
719 36
                            throw AnnotationException::attributeTypeError($propertyName, $originalName, $this->context, 'either a(n) '.$type['array_type'].', or an array of '.$type['array_type'].'s', $item);
720
                        }
721
                    }
722
                }
723 190
            } elseif ($type !== null && gettype($values[$valueName]) !== $type['type'] && !$values[$valueName] instanceof $type['type']) {
724 72
                throw AnnotationException::attributeTypeError($propertyName, $originalName, $this->context, 'a(n) '.$type['value'], $values[$valueName]);
725
            }
726
        }
727
728
        // check if the annotation expects values via the constructor,
729
        // or directly injected into public properties
730 248
        if ($this->metadata->get($name)->usesConstructor()) {
731 210
            return new $name($values);
732
        }
733
734 188
        $instance = new $name();
735
736 188
        foreach ($values as $property => $value) {
737 164
            if (! isset($this->metadata->get($name)->getProperties()[$property])) {
738 93
                if ('value' !== $property) {
739 1
                    throw AnnotationException::creationError(
740 1
                        sprintf(
741 1
                            'The annotation @%s declared on %s does not have a property named "%s". Available properties: %s',
742 1
                            $originalName,
743 1
                            $this->context,
744 1
                            $property,
745 1
                            implode(', ', array_keys($this->metadata->get($name)->getProperties()))
746
                        )
747
                    );
748
                }
749
750 92
                $defaultProperty = $this->metadata->get($name)->getDefaultProperty();
751
752
                // handle the case if the property has no annotations
753 92
                if ($defaultProperty === null) {
754 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)));
755
                }
756
757 90
                $property = $defaultProperty->getName();
758
            }
759
760 161
            $instance->{$property} = $value;
761
        }
762
763 185
        return $instance;
764
    }
765
766
    /**
767
     * MethodCall ::= ["(" [Values] ")"]
768
     *
769
     * @return array
770
     */
771 259
    private function MethodCall()
772
    {
773 259
        $values = [];
774
775 259
        if ( ! $this->lexer->isNextToken(DocLexer::T_OPEN_PARENTHESIS)) {
776 55
            return $values;
777
        }
778
779 242
        $this->match(DocLexer::T_OPEN_PARENTHESIS);
780
781 242
        if ( ! $this->lexer->isNextToken(DocLexer::T_CLOSE_PARENTHESIS)) {
782 242
            $values = $this->Values();
783
        }
784
785 231
        $this->match(DocLexer::T_CLOSE_PARENTHESIS);
786
787 231
        return $values;
788
    }
789
790
    /**
791
     * Values ::= Array | Value {"," Value}* [","]
792
     *
793
     * @return array
794
     */
795 242
    private function Values()
796
    {
797 242
        $values = [$this->Value()];
798
799 231
        while ($this->lexer->isNextToken(DocLexer::T_COMMA)) {
800 94
            $this->match(DocLexer::T_COMMA);
801
802 94
            if ($this->lexer->isNextToken(DocLexer::T_CLOSE_PARENTHESIS)) {
803 1
                break;
804
            }
805
806 93
            $token = $this->lexer->lookahead;
807 93
            $value = $this->Value();
808
809 93
            if ( ! is_object($value) && ! is_array($value)) {
810
                $this->syntaxError('Value', $token);
811
            }
812
813 93
            $values[] = $value;
814
        }
815
816 231
        foreach ($values as $k => $value) {
817 231
            if (is_object($value) && $value instanceof \stdClass) {
818 194
                $values[$value->name] = $value->value;
819 217
            } else if ( ! isset($values['value'])){
820 217
                $values['value'] = $value;
821
            } else {
822 1
                if ( ! is_array($values['value'])) {
823 1
                    $values['value'] = [$values['value']];
824
                }
825
826 1
                $values['value'][] = $value;
827
            }
828
829 231
            unset($values[$k]);
830
        }
831
832 231
        return $values;
833
    }
834
835
    /**
836
     * Constant ::= integer | string | float | boolean
837
     *
838
     * @return mixed
839
     *
840
     * @throws AnnotationException
841
     */
842 74
    private function Constant()
843
    {
844 74
        $identifier = $this->Identifier();
845
846 74
        if ( ! defined($identifier) && false !== strpos($identifier, '::') && '\\' !== $identifier[0]) {
847 16
            list($className, $const) = explode('::', $identifier);
848
849 16
            $pos = strpos($className, '\\');
850 16
            $alias = (false === $pos) ? $className : substr($className, 0, $pos);
851 16
            $found = false;
852 16
            $loweredAlias = strtolower($alias);
853
854
            switch (true) {
855 16
                case !empty ($this->namespaces):
856
                    foreach ($this->namespaces as $ns) {
857
                        if (class_exists($ns.'\\'.$className) || interface_exists($ns.'\\'.$className)) {
858
                             $className = $ns.'\\'.$className;
859
                             $found = true;
860
                             break;
861
                        }
862
                    }
863
                    break;
864
865 16
                case isset($this->imports[$loweredAlias]):
866 14
                    $found     = true;
867 14
                    $className = (false !== $pos)
868
                        ? $this->imports[$loweredAlias] . substr($className, $pos)
869 14
                        : $this->imports[$loweredAlias];
870 14
                    break;
871
872
                default:
873 2
                    if(isset($this->imports['__NAMESPACE__'])) {
874
                        $ns = $this->imports['__NAMESPACE__'];
875
876
                        if (class_exists($ns.'\\'.$className) || interface_exists($ns.'\\'.$className)) {
877
                            $className = $ns.'\\'.$className;
878
                            $found = true;
879
                        }
880
                    }
881 2
                    break;
882
            }
883
884 16
            if ($found) {
885 14
                 $identifier = $className . '::' . $const;
886
            }
887
        }
888
889
        // checks if identifier ends with ::class, \strlen('::class') === 7
890 74
        $classPos = stripos($identifier, '::class');
891 74
        if ($classPos === strlen($identifier) - 7) {
892 4
            return substr($identifier, 0, $classPos);
893
        }
894
895 70
        if (!defined($identifier)) {
896 1
            throw AnnotationException::semanticalErrorConstants($identifier, $this->context);
897
        }
898
899 69
        return constant($identifier);
900
    }
901
902
    /**
903
     * Identifier ::= string
904
     *
905
     * @return string
906
     */
907 289
    private function Identifier()
908
    {
909
        // check if we have an annotation
910 289
        if ( ! $this->lexer->isNextTokenAny(self::$classIdentifiers)) {
911 8
            $this->syntaxError('namespace separator or identifier');
912
        }
913
914 289
        $this->lexer->moveNext();
915
916 289
        $className = $this->lexer->token['value'];
917
918 289
        while ($this->lexer->lookahead['position'] === ($this->lexer->token['position'] + strlen($this->lexer->token['value']))
919 289
                && $this->lexer->isNextToken(DocLexer::T_NAMESPACE_SEPARATOR)) {
920
921 1
            $this->match(DocLexer::T_NAMESPACE_SEPARATOR);
922 1
            $this->matchAny(self::$classIdentifiers);
923
924
            $className .= '\\' . $this->lexer->token['value'];
925
        }
926
927 288
        return $className;
928
    }
929
930
    /**
931
     * Value ::= PlainValue | FieldAssignment
932
     *
933
     * @return mixed
934
     */
935 242
    private function Value()
936
    {
937 242
        $peek = $this->lexer->glimpse();
938
939 242
        if (DocLexer::T_EQUALS === $peek['type']) {
940 196
            return $this->FieldAssignment();
941
        }
942
943 227
        return $this->PlainValue();
944
    }
945
946
    /**
947
     * PlainValue ::= integer | string | float | boolean | Array | Annotation
948
     *
949
     * @return mixed
950
     */
951 242
    private function PlainValue()
952
    {
953 242
        if ($this->lexer->isNextToken(DocLexer::T_OPEN_CURLY_BRACES)) {
954 138
            return $this->Arrayx();
955
        }
956
957 241
        if ($this->lexer->isNextToken(DocLexer::T_AT)) {
958 113
            return $this->Annotation();
959
        }
960
961 233
        if ($this->lexer->isNextToken(DocLexer::T_IDENTIFIER)) {
962 74
            return $this->Constant();
963
        }
964
965 232
        switch ($this->lexer->lookahead['type']) {
966 232
            case DocLexer::T_STRING:
967 225
                $this->match(DocLexer::T_STRING);
968 225
                return $this->lexer->token['value'];
969
970 81
            case DocLexer::T_INTEGER:
971 53
                $this->match(DocLexer::T_INTEGER);
972 53
                return (int)$this->lexer->token['value'];
973
974 30
            case DocLexer::T_FLOAT:
975 28
                $this->match(DocLexer::T_FLOAT);
976 28
                return (float)$this->lexer->token['value'];
977
978 2
            case DocLexer::T_TRUE:
979
                $this->match(DocLexer::T_TRUE);
980
                return true;
981
982 2
            case DocLexer::T_FALSE:
983
                $this->match(DocLexer::T_FALSE);
984
                return false;
985
986 2
            case DocLexer::T_NULL:
987
                $this->match(DocLexer::T_NULL);
988
                return null;
989
990
            default:
991 2
                $this->syntaxError('PlainValue');
992
        }
993
    }
994
995
    /**
996
     * FieldAssignment ::= FieldName "=" PlainValue
997
     * FieldName ::= identifier
998
     *
999
     * @return \stdClass
1000
     */
1001 196
    private function FieldAssignment()
1002
    {
1003 196
        $this->match(DocLexer::T_IDENTIFIER);
1004 196
        $fieldName = $this->lexer->token['value'];
1005
1006 196
        $this->match(DocLexer::T_EQUALS);
1007
1008 196
        $item = new \stdClass();
1009 196
        $item->name  = $fieldName;
1010 196
        $item->value = $this->PlainValue();
1011
1012 194
        return $item;
1013
    }
1014
1015
    /**
1016
     * Array ::= "{" ArrayEntry {"," ArrayEntry}* [","] "}"
1017
     *
1018
     * @return array
1019
     */
1020 138
    private function Arrayx()
1021
    {
1022 138
        $array = $values = [];
1023
1024 138
        $this->match(DocLexer::T_OPEN_CURLY_BRACES);
1025
1026
        // If the array is empty, stop parsing and return.
1027 138
        if ($this->lexer->isNextToken(DocLexer::T_CLOSE_CURLY_BRACES)) {
1028 1
            $this->match(DocLexer::T_CLOSE_CURLY_BRACES);
1029
1030 1
            return $array;
1031
        }
1032
1033 138
        $values[] = $this->ArrayEntry();
1034
1035 138
        while ($this->lexer->isNextToken(DocLexer::T_COMMA)) {
1036 119
            $this->match(DocLexer::T_COMMA);
1037
1038
            // optional trailing comma
1039 119
            if ($this->lexer->isNextToken(DocLexer::T_CLOSE_CURLY_BRACES)) {
1040 86
                break;
1041
            }
1042
1043 119
            $values[] = $this->ArrayEntry();
1044
        }
1045
1046 138
        $this->match(DocLexer::T_CLOSE_CURLY_BRACES);
1047
1048 138
        foreach ($values as $value) {
1049 138
            list ($key, $val) = $value;
1050
1051 138
            if ($key !== null) {
1052 13
                $array[$key] = $val;
1053
            } else {
1054 129
                $array[] = $val;
1055
            }
1056
        }
1057
1058 138
        return $array;
1059
    }
1060
1061
    /**
1062
     * ArrayEntry ::= Value | KeyValuePair
1063
     * KeyValuePair ::= Key ("=" | ":") PlainValue | Constant
1064
     * Key ::= string | integer | Constant
1065
     *
1066
     * @return array
1067
     */
1068 138
    private function ArrayEntry()
1069
    {
1070 138
        $peek = $this->lexer->glimpse();
1071
1072 138
        if (DocLexer::T_EQUALS === $peek['type']
1073 138
                || DocLexer::T_COLON === $peek['type']) {
1074
1075 13
            if ($this->lexer->isNextToken(DocLexer::T_IDENTIFIER)) {
1076 5
                $key = $this->Constant();
1077
            } else {
1078 8
                $this->matchAny([DocLexer::T_INTEGER, DocLexer::T_STRING]);
1079 8
                $key = $this->lexer->token['value'];
1080
            }
1081
1082 13
            $this->matchAny([DocLexer::T_EQUALS, DocLexer::T_COLON]);
1083
1084 13
            return [$key, $this->PlainValue()];
1085
        }
1086
1087 129
        return [null, $this->Value()];
1088
    }
1089
1090
    /**
1091
     * Checks whether the given $name matches any ignored annotation name or namespace
1092
     *
1093
     * @param string $name
1094
     *
1095
     * @return bool
1096
     */
1097 286
    private function isIgnoredAnnotation($name)
1098
    {
1099 286
        if ($this->ignoreNotImportedAnnotations || isset($this->ignoredAnnotationNames[$name])) {
1100 270
            return true;
1101
        }
1102
1103 17
        foreach (array_keys($this->ignoredAnnotationNamespaces) as $ignoredAnnotationNamespace) {
1104 15
            $ignoredAnnotationNamespace = rtrim($ignoredAnnotationNamespace, '\\') . '\\';
1105
1106 15
            if (0 === stripos(rtrim($name, '\\') . '\\', $ignoredAnnotationNamespace)) {
1107 15
                return true;
1108
            }
1109
        }
1110
1111 2
        return false;
1112
    }
1113
}
1114