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

DocParser::collectAnnotationMetadata()   D

Complexity

Conditions 19
Paths 84

Size

Total Lines 102
Code Lines 57

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 53
CRAP Score 19.0173

Importance

Changes 0
Metric Value
eloc 57
dl 0
loc 102
ccs 53
cts 55
cp 0.9636
rs 4.5166
c 0
b 0
f 0
cc 19
nc 84
nop 1
crap 19.0173

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 ReflectionClass;
12
use Doctrine\Annotations\Annotation\Enum;
13
use Doctrine\Annotations\Annotation\Target;
14
use Doctrine\Annotations\Annotation\Attributes;
15
use function array_key_exists;
16
use function array_keys;
17
18
/**
19
 * A parser for docblock annotations.
20
 *
21
 * It is strongly discouraged to change the default annotation parsing process.
22
 *
23
 * @author Benjamin Eberlei <[email protected]>
24
 * @author Guilherme Blanco <[email protected]>
25
 * @author Jonathan Wage <[email protected]>
26
 * @author Roman Borschel <[email protected]>
27
 * @author Johannes M. Schmitt <[email protected]>
28
 * @author Fabio B. Silva <[email protected]>
29
 */
30
final class DocParser
31
{
32
    /**
33
     * An array of all valid tokens for a class name.
34
     *
35
     * @var array
36
     */
37
    private static $classIdentifiers = [
38
        DocLexer::T_IDENTIFIER,
39
        DocLexer::T_TRUE,
40
        DocLexer::T_FALSE,
41
        DocLexer::T_NULL
42
    ];
43
44
    /**
45
     * The lexer.
46
     *
47
     * @var \Doctrine\Annotations\DocLexer
48
     */
49
    private $lexer;
50
51
    /**
52
     * Current target context.
53
     *
54
     * @var integer
55
     */
56
    private $target;
57
58
    /**
59
     * Doc parser used to collect annotation target.
60
     *
61
     * @var \Doctrine\Annotations\DocParser
62
     */
63
    private static $metadataParser;
64
65
    /**
66
     * Flag to control if the current annotation is nested or not.
67
     *
68
     * @var boolean
69
     */
70
    private $isNestedAnnotation = false;
71
72
    /**
73
     * Hashmap containing all use-statements that are to be used when parsing
74
     * the given doc block.
75
     *
76
     * @var array
77
     */
78
    private $imports = [];
79
80
    /**
81
     * This hashmap is used internally to cache results of class_exists()
82
     * look-ups.
83
     *
84
     * @var array
85
     */
86
    private $classExists = [];
87
88
    /**
89
     * Whether annotations that have not been imported should be ignored.
90
     *
91
     * @var boolean
92
     */
93
    private $ignoreNotImportedAnnotations = false;
94
95
    /**
96
     * An array of default namespaces if operating in simple mode.
97
     *
98
     * @var string[]
99
     */
100
    private $namespaces = [];
101
102
    /**
103
     * A list with annotations that are not causing exceptions when not resolved to an annotation class.
104
     *
105
     * The names must be the raw names as used in the class, not the fully qualified
106
     * class names.
107
     *
108
     * @var bool[] indexed by annotation name
109
     */
110
    private $ignoredAnnotationNames = [];
111
112
    /**
113
     * A list with annotations in namespaced format
114
     * that are not causing exceptions when not resolved to an annotation class.
115
     *
116
     * @var bool[] indexed by namespace name
117
     */
118
    private $ignoredAnnotationNamespaces = [];
119
120
    /**
121
     * @var string
122
     */
123
    private $context = '';
124
125
    /**
126
     * Hash-map for caching annotation metadata.
127
     *
128
     * @var MetadataCollection
129
     */
130
    private $annotationMetadata;
131
132
    /** @var array<string, bool> */
133
    private $nonAnnotationClasses = [];
134
135
    /**
136
     * Hash-map for handle types declaration.
137
     *
138
     * @var array
139
     */
140
    private static $typeMap = [
141
        'float'     => 'double',
142
        'bool'      => 'boolean',
143
        // allow uppercase Boolean in honor of George Boole
144
        'Boolean'   => 'boolean',
145
        'int'       => 'integer',
146
    ];
147
148
    /**
149
     * Constructs a new DocParser.
150
     */
151 290
    public function __construct()
152
    {
153 290
        $this->lexer              = new DocLexer;
154 290
        $this->annotationMetadata = InternalAnnotations::createMetadata();
155 290
    }
156
157
    /**
158
     * Sets the annotation names that are ignored during the parsing process.
159
     *
160
     * The names are supposed to be the raw names as used in the class, not the
161
     * fully qualified class names.
162
     *
163
     * @param bool[] $names indexed by annotation name
164
     *
165
     * @return void
166
     */
167 47
    public function setIgnoredAnnotationNames(array $names)
168
    {
169 47
        $this->ignoredAnnotationNames = $names;
170 47
    }
171
172
    /**
173
     * Sets the annotation namespaces that are ignored during the parsing process.
174
     *
175
     * @param bool[] $ignoredAnnotationNamespaces indexed by annotation namespace name
176
     *
177
     * @return void
178
     */
179 58
    public function setIgnoredAnnotationNamespaces($ignoredAnnotationNamespaces)
180
    {
181 58
        $this->ignoredAnnotationNamespaces = $ignoredAnnotationNamespaces;
182 58
    }
183
184
    /**
185
     * Sets ignore on not-imported annotations.
186
     *
187
     * @param boolean $bool
188
     *
189
     * @return void
190
     */
191 270
    public function setIgnoreNotImportedAnnotations($bool)
192
    {
193 270
        $this->ignoreNotImportedAnnotations = (boolean) $bool;
194 270
    }
195
196
    /**
197
     * Sets the default namespaces.
198
     *
199
     * @param string $namespace
200
     *
201
     * @return void
202
     *
203
     * @throws \RuntimeException
204
     */
205 2
    public function addNamespace($namespace)
206
    {
207 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...
208
            throw new \RuntimeException('You must either use addNamespace(), or setImports(), but not both.');
209
        }
210
211 2
        $this->namespaces[] = $namespace;
212 2
    }
213
214
    /**
215
     * Sets the imports.
216
     *
217
     * @param array $imports
218
     *
219
     * @return void
220
     *
221
     * @throws \RuntimeException
222
     */
223 269
    public function setImports(array $imports)
224
    {
225 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...
226
            throw new \RuntimeException('You must either use addNamespace(), or setImports(), but not both.');
227
        }
228
229 269
        $this->imports = $imports;
230 269
    }
231
232
    /**
233
     * Sets current target context as bitmask.
234
     *
235
     * @param integer $target
236
     *
237
     * @return void
238
     */
239 271
    public function setTarget($target)
240
    {
241 271
        $this->target = $target;
242 271
    }
243
244
    /**
245
     * Parses the given docblock string for annotations.
246
     *
247
     * @param string $input   The docblock string to parse.
248
     * @param string $context The parsing context.
249
     *
250
     * @return array Array of annotations. If no annotations are found, an empty array is returned.
251
     */
252 290
    public function parse($input, $context = '')
253
    {
254 290
        $pos = $this->findInitialTokenPosition($input);
255 290
        if ($pos === null) {
256 19
            return [];
257
        }
258
259 289
        $this->context = $context;
260
261 289
        $this->lexer->setInput(trim(substr($input, $pos), '* /'));
262 289
        $this->lexer->moveNext();
263
264 289
        return $this->Annotations();
265
    }
266
267
    /**
268
     * Finds the first valid annotation
269
     *
270
     * @param string $input The docblock string to parse
271
     *
272
     * @return int|null
273
     */
274 290
    private function findInitialTokenPosition($input)
275
    {
276 290
        $pos = 0;
277
278
        // search for first valid annotation
279 290
        while (($pos = strpos($input, '@', $pos)) !== false) {
280 290
            $preceding = substr($input, $pos - 1, 1);
281
282
            // if the @ is preceded by a space, a tab or * it is valid
283 290
            if ($pos === 0 || $preceding === ' ' || $preceding === '*' || $preceding === "\t") {
284 289
                return $pos;
285
            }
286
287 2
            $pos++;
288
        }
289
290 19
        return null;
291
    }
292
293
    /**
294
     * Attempts to match the given token with the current lookahead token.
295
     * If they match, updates the lookahead token; otherwise raises a syntax error.
296
     *
297
     * @param integer $token Type of token.
298
     *
299
     * @return boolean True if tokens match; false otherwise.
300
     */
301 289
    private function match($token)
302
    {
303 289
        if ( ! $this->lexer->isNextToken($token) ) {
304
            $this->syntaxError($this->lexer->getLiteral($token));
305
        }
306
307 289
        return $this->lexer->moveNext();
308
    }
309
310
    /**
311
     * Attempts to match the current lookahead token with any of the given tokens.
312
     *
313
     * If any of them matches, this method updates the lookahead token; otherwise
314
     * a syntax error is raised.
315
     *
316
     * @param array $tokens
317
     *
318
     * @return boolean
319
     */
320 14
    private function matchAny(array $tokens)
321
    {
322 14
        if ( ! $this->lexer->isNextTokenAny($tokens)) {
323 1
            $this->syntaxError(implode(' or ', array_map([$this->lexer, 'getLiteral'], $tokens)));
324
        }
325
326 13
        return $this->lexer->moveNext();
327
    }
328
329
    /**
330
     * Generates a new syntax error.
331
     *
332
     * @param string     $expected Expected string.
333
     * @param array|null $token    Optional token.
334
     *
335
     * @return void
336
     *
337
     * @throws AnnotationException
338
     */
339 11
    private function syntaxError($expected, $token = null)
340
    {
341 11
        if ($token === null) {
342 11
            $token = $this->lexer->lookahead;
343
        }
344
345 11
        $message  = sprintf('Expected %s, got ', $expected);
346 11
        $message .= ($this->lexer->lookahead === null)
347
            ? 'end of string'
348 11
            : sprintf("'%s' at position %s", $token['value'], $token['position']);
349
350 11
        if (strlen($this->context)) {
351 8
            $message .= ' in ' . $this->context;
352
        }
353
354 11
        $message .= '.';
355
356 11
        throw AnnotationException::syntaxError($message);
357
    }
358
359
    /**
360
     * Attempts to check if a class exists or not. This always uses PHP autoloading mechanism.
361
     *
362
     * @param string $fqcn
363
     *
364
     * @return boolean
365
     */
366 284
    private function classExists($fqcn)
367
    {
368 284
        if (isset($this->classExists[$fqcn])) {
369 240
            return $this->classExists[$fqcn];
370
        }
371
372
        // final check, does this class exist?
373 284
        return $this->classExists[$fqcn] = class_exists($fqcn);
374
    }
375
376
    /**
377
     * Collects parsing metadata for a given annotation class
378
     *
379
     * @param string $name The annotation name
380
     *
381
     * @return void
382
     */
383 263
    private function collectAnnotationMetadata($name)
384
    {
385 263
        if (self::$metadataParser === null) {
386 1
            self::$metadataParser = new self();
387
388 1
            self::$metadataParser->setIgnoreNotImportedAnnotations(true);
389 1
            self::$metadataParser->setIgnoredAnnotationNames($this->ignoredAnnotationNames);
390 1
            self::$metadataParser->setImports([
391 1
                'enum'          => 'Doctrine\Annotations\Annotation\Enum',
392
                'target'        => 'Doctrine\Annotations\Annotation\Target',
393
                'attribute'     => 'Doctrine\Annotations\Annotation\Attribute',
394
                'attributes'    => 'Doctrine\Annotations\Annotation\Attributes'
395
            ]);
396
        }
397
398 263
        $class          = new \ReflectionClass($name);
399 263
        $docComment     = $class->getDocComment();
400 263
        $constructor    = $class->getConstructor();
401 263
        $useConstructor = $constructor !== null && $constructor->getNumberOfParameters() > 0;
402
403
        // verify that the class is really meant to be an annotation
404 263
        if (strpos($docComment, '@Annotation') === false) {
405 4
            $this->nonAnnotationClasses[$name] = true;
406 4
            return;
407
        }
408
409 259
        $annotationBuilder = new AnnotationMetadataBuilder($name);
410
411 259
        if ($useConstructor) {
412 89
            $annotationBuilder = $annotationBuilder->withUsingConstructor();
413
        }
414
415 259
        self::$metadataParser->setTarget(Target::TARGET_CLASS);
416
417 259
        foreach (self::$metadataParser->parse($docComment, 'class @' . $name) as $annotation) {
418 203
            if ($annotation instanceof Target) {
419 203
                $annotationBuilder = $annotationBuilder->withTarget(AnnotationTarget::fromAnnotation($annotation));
420
421 203
                continue;
422
            }
423
424 84
            if ($annotation instanceof Attributes) {
425 84
                foreach ($annotation->value as $attribute) {
426 84
                    $annotationBuilder = $annotationBuilder->withProperty(
427 84
                        $this->collectAttributeTypeMetadata(new PropertyMetadataBuilder($attribute->name), $attribute)->build()
428
                    );
429
                }
430
            }
431
        }
432
433
        // if there is no constructor we will inject values into public properties
434 253
        if (! $useConstructor) {
435
            // collect all public properties
436 182
            foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $i => $property) {
437 168
                $propertyBuilder = new PropertyMetadataBuilder($property->getName());
438 168
                $propertyComment = $property->getDocComment();
439
440 168
                if ($i === 0) {
441 168
                    $propertyBuilder = $propertyBuilder->withBeingDefault();
442
                }
443
444
445 168
                if ($propertyComment === false) {
446 73
                    $annotationBuilder = $annotationBuilder->withProperty($propertyBuilder->build());
447
448 73
                    continue;
449
                }
450
451 113
                $attribute           = new Attribute();
452 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

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

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

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