Failed Conditions
Pull Request — master (#247)
by Michael
13:16
created

DocParser::collectAttributeTypeMetadata()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 42
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 5.0164

Importance

Changes 0
Metric Value
eloc 18
dl 0
loc 42
rs 9.3554
c 0
b 0
f 0
ccs 21
cts 23
cp 0.913
cc 5
nc 7
nop 2
crap 5.0164
1
<?php
2
3
namespace Doctrine\Annotations;
4
5
use function array_key_exists;
6
use function array_keys;
7
use Doctrine\Annotations\Annotation\Attribute;
8
use Doctrine\Annotations\Metadata\AnnotationTarget;
9
use Doctrine\Annotations\Metadata\Builder\AnnotationMetadataBuilder;
10
use Doctrine\Annotations\Metadata\Builder\PropertyMetadataBuilder;
11
use Doctrine\Annotations\Metadata\InternalAnnotations;
12
use Doctrine\Annotations\Metadata\MetadataCollection;
13
use ReflectionClass;
14
use Doctrine\Annotations\Annotation\Enum;
15
use Doctrine\Annotations\Annotation\Target;
16
use Doctrine\Annotations\Annotation\Attributes;
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
    public function __construct()
152
    {
153
        $this->lexer              = new DocLexer;
154
        $this->annotationMetadata = InternalAnnotations::createMetadata();
155
    }
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
    public function setIgnoredAnnotationNames(array $names)
168
    {
169
        $this->ignoredAnnotationNames = $names;
170
    }
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
    public function setIgnoredAnnotationNamespaces($ignoredAnnotationNamespaces)
180
    {
181
        $this->ignoredAnnotationNamespaces = $ignoredAnnotationNamespaces;
182
    }
183
184
    /**
185
     * Sets ignore on not-imported annotations.
186
     *
187
     * @param boolean $bool
188
     *
189
     * @return void
190
     */
191
    public function setIgnoreNotImportedAnnotations($bool)
192
    {
193
        $this->ignoreNotImportedAnnotations = (boolean) $bool;
194
    }
195
196
    /**
197
     * Sets the default namespaces.
198
     *
199
     * @param string $namespace
200
     *
201
     * @return void
202
     *
203
     * @throws \RuntimeException
204
     */
205
    public function addNamespace($namespace)
206
    {
207
        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
        $this->namespaces[] = $namespace;
212
    }
213
214
    /**
215
     * Sets the imports.
216
     *
217
     * @param array $imports
218
     *
219
     * @return void
220
     *
221
     * @throws \RuntimeException
222
     */
223
    public function setImports(array $imports)
224
    {
225 330
        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 330
        }
228 330
229
        $this->imports = $imports;
230
    }
231
232
    /**
233
     * Sets current target context as bitmask.
234
     *
235
     * @param integer $target
236
     *
237
     * @return void
238
     */
239
    public function setTarget($target)
240 87
    {
241
        $this->target = $target;
242 87
    }
243 87
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 97
    public function parse($input, $context = '')
253
    {
254 97
        $pos = $this->findInitialTokenPosition($input);
255 97
        if ($pos === null) {
256
            return [];
257
        }
258
259
        $this->context = $context;
260
261
        $this->lexer->setInput(trim(substr($input, $pos), '* /'));
262
        $this->lexer->moveNext();
263
264 310
        return $this->Annotations();
265
    }
266 310
267 310
    /**
268
     * Finds the first valid annotation
269
     *
270
     * @param string $input The docblock string to parse
271
     *
272
     * @return int|null
273
     */
274
    private function findInitialTokenPosition($input)
275
    {
276
        $pos = 0;
277
278 2
        // search for first valid annotation
279
        while (($pos = strpos($input, '@', $pos)) !== false) {
280 2
            $preceding = substr($input, $pos - 1, 1);
281
282
            // if the @ is preceded by a space, a tab or * it is valid
283
            if ($pos === 0 || $preceding === ' ' || $preceding === '*' || $preceding === "\t") {
284 2
                return $pos;
285 2
            }
286
287
            $pos++;
288
        }
289
290
        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 309
     *
297
     * @param integer $token Type of token.
298 309
     *
299
     * @return boolean True if tokens match; false otherwise.
300
     */
301
    private function match($token)
302 309
    {
303 309
        if ( ! $this->lexer->isNextToken($token) ) {
304
            $this->syntaxError($this->lexer->getLiteral($token));
305
        }
306
307
        return $this->lexer->moveNext();
308
    }
309
310
    /**
311
     * Attempts to match the current lookahead token with any of the given tokens.
312 270
     *
313
     * If any of them matches, this method updates the lookahead token; otherwise
314 270
     * a syntax error is raised.
315 270
     *
316
     * @param array $tokens
317
     *
318
     * @return boolean
319
     */
320
    private function matchAny(array $tokens)
321
    {
322
        if ( ! $this->lexer->isNextTokenAny($tokens)) {
323
            $this->syntaxError(implode(' or ', array_map([$this->lexer, 'getLiteral'], $tokens)));
324
        }
325 329
326
        return $this->lexer->moveNext();
327 329
    }
328 329
329 32
    /**
330
     * Generates a new syntax error.
331
     *
332 328
     * @param string     $expected Expected string.
333
     * @param array|null $token    Optional token.
334 328
     *
335 328
     * @return void
336
     *
337 328
     * @throws AnnotationException
338
     */
339
    private function syntaxError($expected, $token = null)
340
    {
341
        if ($token === null) {
342
            $token = $this->lexer->lookahead;
343
        }
344
345
        $message  = sprintf('Expected %s, got ', $expected);
346
        $message .= ($this->lexer->lookahead === null)
347 329
            ? 'end of string'
348
            : sprintf("'%s' at position %s", $token['value'], $token['position']);
349 329
350
        if (strlen($this->context)) {
351
            $message .= ' in ' . $this->context;
352 329
        }
353 329
354
        $message .= '.';
355
356 329
        throw AnnotationException::syntaxError($message);
357 328
    }
358
359
    /**
360 3
     * Attempts to check if a class exists or not. This always uses PHP autoloading mechanism.
361
     *
362
     * @param string $fqcn
363 32
     *
364
     * @return boolean
365
     */
366
    private function classExists($fqcn)
367
    {
368
        if (isset($this->classExists[$fqcn])) {
369
            return $this->classExists[$fqcn];
370
        }
371
372
        // final check, does this class exist?
373
        return $this->classExists[$fqcn] = class_exists($fqcn);
374 328
    }
375
376 328
    /**
377
     * Collects parsing metadata for a given annotation class
378
     *
379
     * @param string $name The annotation name
380 328
     *
381
     * @return void
382
     */
383
    private function collectAnnotationMetadata($name)
384
    {
385
        if (self::$metadataParser === null) {
386
            self::$metadataParser = new self();
387
388
            self::$metadataParser->setIgnoreNotImportedAnnotations(true);
389
            self::$metadataParser->setIgnoredAnnotationNames($this->ignoredAnnotationNames);
390
            self::$metadataParser->setImports([
391
                'enum'          => 'Doctrine\Annotations\Annotation\Enum',
392
                'target'        => 'Doctrine\Annotations\Annotation\Target',
393 14
                'attribute'     => 'Doctrine\Annotations\Annotation\Attribute',
394
                'attributes'    => 'Doctrine\Annotations\Annotation\Attributes'
395 14
            ]);
396 1
        }
397
398
        $class          = new \ReflectionClass($name);
399 13
        $docComment     = $class->getDocComment();
400
        $constructor    = $class->getConstructor();
401
        $useConstructor = $constructor !== null && $constructor->getNumberOfParameters() > 0;
402
403
        // verify that the class is really meant to be an annotation
404
        if (strpos($docComment, '@Annotation') === false) {
405
            $this->nonAnnotationClasses[$name] = true;
406
            return;
407
        }
408
409
        $annotationBuilder = new AnnotationMetadataBuilder($name);
410
411
        if ($useConstructor) {
412 17
            $annotationBuilder = $annotationBuilder->withUsingConstructor();
413
        }
414 17
415 17
        self::$metadataParser->setTarget(Target::TARGET_CLASS);
416
417
        foreach (self::$metadataParser->parse($docComment, 'class @' . $name) as $annotation) {
418 17
            if ($annotation instanceof Target) {
419 17
                $annotationBuilder = $annotationBuilder->withTarget(AnnotationTarget::fromAnnotation($annotation));
420
421 17
                continue;
422
            }
423 17
424 14
            if ($annotation instanceof Attributes) {
425
                foreach ($annotation->value as $attribute) {
426
                    $annotationBuilder = $annotationBuilder->withProperty(
427 17
                        $this->collectAttributeTypeMetadata(new PropertyMetadataBuilder($attribute->name), $attribute)->build()
428
                    );
429 17
                }
430
            }
431
        }
432
433
        // if there is no constructor we will inject values into public properties
434
        if (! $useConstructor) {
435
            // collect all public properties
436
            foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $i => $property) {
437
                $propertyBuilder = new PropertyMetadataBuilder($property->getName());
438
                $propertyComment = $property->getDocComment();
439 320
440
                if ($i === 0) {
441 320
                    $propertyBuilder = $propertyBuilder->withBeingDefault();
442 236
                }
443
444
445
                if ($propertyComment === false) {
446 320
                    $annotationBuilder = $annotationBuilder->withProperty($propertyBuilder->build());
447
448
                    continue;
449
                }
450
451
                $attribute           = new Attribute();
452
                $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
                $attribute->name     = $property->name;
454
                $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
                    ? $matches[1]
456 41
                    : 'mixed';
457
458 41
                $propertyBuilder = $this->collectAttributeTypeMetadata($propertyBuilder, $attribute);
459 1
460
                // checks if the property has @Enum
461 1
                if (false !== strpos($propertyComment, '@Enum')) {
462 1
                    $context = 'property ' . $class->name . "::\$" . $property->name;
463 1
464 1
                    self::$metadataParser->setTarget(Target::TARGET_PROPERTY);
465
466
                    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
                        if ( ! $annotation instanceof Enum) {
468
                            continue;
469
                        }
470
471 41
                        $propertyBuilder = $propertyBuilder->withEnum([
472 41
                            'value'   => $annotation->value,
473
                            'literal' => ( ! empty($annotation->literal))
474
                                ? $annotation->literal
475
                                : $annotation->value,
476 41
                        ]);
477 41
                    }
478
                }
479
480
                $annotationBuilder = $annotationBuilder->withProperty($propertyBuilder->build());
481
            }
482
        }
483 41
484
        $this->annotationMetadata[] = $annotationBuilder->build();
485
    }
486
487 41
    /**
488 38
     * Collects parsing metadata for a given attribute.
489
     *
490 38
     * @param array     $metadata
491 10
     * @param Attribute $attribute
492 10
     */
493 10
    private function collectAttributeTypeMetadata(
494
        PropertyMetadataBuilder $metadata,
495 10
        Attribute $attribute
496
    ) : PropertyMetadataBuilder
497
    {
498 2
        // handle internal type declaration
499 2
        $type = self::$typeMap[$attribute->type] ?? $attribute->type;
500 2
501
        // handle the case if the property type is mixed
502
        if ('mixed' === $type) {
503
            return $metadata;
504
        }
505
506 29
        if ($attribute->required) {
507
            $metadata = $metadata->withBeingRequired();
508 20
        }
509 13
510
        // Evaluate type
511 13
512 5
        // Checks if the property has array<type>
513
        if (false !== $pos = strpos($type, '<')) {
514
            $arrayType = substr($type, $pos + 1, -1);
515 9
516
            return $metadata->withType([
517 9
                'type' => 'array',
518 9
                'array_type' => self::$typeMap[$arrayType] ?? $arrayType,
519 9
            ]);
520 9
        }
521
522
        // Checks if the property has type[]
523 9
         if (false !== $pos = strrpos($type, '[')) {
524
            $arrayType = substr($type, 0, $pos);
525
526 9
            return $metadata->withType([
527 4
                'type'            => 'array',
528
                'array_type' => self::$typeMap[$arrayType] ?? $arrayType,
529 4
            ]);
530
        }
531 4
532 2
        return $metadata->withType([
533
            'type'  => $type,
534
            'value' => $attribute->type,
535
        ]);
536 2
    }
537 2
538 1
    /**
539 1
     * Annotations ::= Annotation {[ "*" ]* [Annotation]}*
540
     *
541
     * @return array
542
     */
543
    private function Annotations()
544
    {
545 18
        $annotations = [];
546
547
        while (null !== $this->lexer->lookahead) {
548
            if (DocLexer::T_AT !== $this->lexer->lookahead['type']) {
549 30
                $this->lexer->moveNext();
550 30
                continue;
551
            }
552
553
            // make sure the @ is preceded by non-catchable pattern
554
            if (null !== $this->lexer->token && $this->lexer->lookahead['position'] === $this->lexer->token['position'] + strlen($this->lexer->token['value'])) {
555
                $this->lexer->moveNext();
556
                continue;
557
            }
558
559
            // make sure the @ is followed by either a namespace separator, or
560 11
            // an identifier token
561
            if ((null === $peek = $this->lexer->glimpse())
562
                || (DocLexer::T_NAMESPACE_SEPARATOR !== $peek['type'] && !in_array($peek['type'], self::$classIdentifiers, true))
563 11
                || $peek['position'] !== $this->lexer->lookahead['position'] + 1) {
564
                $this->lexer->moveNext();
565
                continue;
566 11
            }
567 7
568
            $this->isNestedAnnotation = false;
569
            if (false !== $annot = $this->Annotation()) {
570
                $annotations[] = $annot;
571
            }
572
        }
573 6
574 2
        return $annotations;
575 2
    }
576
577 2
    /**
578
     * Annotation     ::= "@" AnnotationName MethodCall
579
     * AnnotationName ::= QualifiedName | SimpleName
580
     * QualifiedName  ::= NameSpacePart "\" {NameSpacePart "\"}* SimpleName
581 2
     * NameSpacePart  ::= identifier | null | false | true
582 2
     * SimpleName     ::= identifier | null | false | true
583
     *
584
     * @return mixed False if it is not a valid annotation.
585 6
     *
586 2
     * @throws AnnotationException
587 2
     */
588
    private function Annotation()
589 2
    {
590
        $this->match(DocLexer::T_AT);
591
592
        // check if we have an annotation
593 2
        $name = $this->Identifier();
594 2
595
        // only process names which are not fully qualified, yet
596
        // fully qualified names must start with a \
597 6
        $originalName = $name;
598 6
599 6
        if ('\\' !== $name[0]) {
600 6
            $pos = strpos($name, '\\');
601
            $alias = (false === $pos)? $name : substr($name, 0, $pos);
602
            $found = false;
603
            $loweredAlias = strtolower($alias);
604
605
            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
                foreach ($this->namespaces as $namespace) {
607 328
                    if ($this->classExists($namespace.'\\'.$name)) {
608
                        $name = $namespace.'\\'.$name;
609 328
                        $found = true;
610
                        break;
611 328
                    }
612 328
                }
613 56
            } elseif (isset($this->imports[$loweredAlias])) {
614 56
                $found = true;
615
                $name  = (false !== $pos)
616
                    ? $this->imports[$loweredAlias] . substr($name, $pos)
617
                    : $this->imports[$loweredAlias];
618 328
            } elseif ( ! isset($this->ignoredAnnotationNames[$name])
619 9
                && isset($this->imports['__NAMESPACE__'])
620 9
                && $this->classExists($this->imports['__NAMESPACE__'] . '\\' . $name)
621
            ) {
622
                $name  = $this->imports['__NAMESPACE__'].'\\'.$name;
623
                $found = true;
624
            } elseif (! isset($this->ignoredAnnotationNames[$name]) && $this->classExists($name)) {
625 328
                $found = true;
626 328
            }
627 328
628 2
            if ( ! $found) {
629 2
                if ($this->isIgnoredAnnotation($name)) {
630
                    return false;
631
                }
632 328
633 328
                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 151
            }
635
        }
636
637
        $name = ltrim($name,'\\');
638 198
639
        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
        if (! isset($this->annotationMetadata[$name]) && ! array_key_exists($name, $this->nonAnnotationClasses)) {
650
            $this->collectAnnotationMetadata($name);
651
        }
652 328
653
        // verify that the class is really meant to be an annotation and not just any ordinary class
654 328
        if (array_key_exists($name, $this->nonAnnotationClasses)) {
655
            if ($this->ignoreNotImportedAnnotations || isset($this->ignoredAnnotationNames[$originalName])) {
656
                return false;
657 328
            }
658
659
            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 327
662
        //if target is nested annotation
663 327
        $target = $this->isNestedAnnotation ? Target::TARGET_ANNOTATION : $this->target;
664 323
665 323
        // Next will be nested
666 323
        $this->isNestedAnnotation = true;
667 323
668
        //if annotation does not support current target
669 323
        if (($this->annotationMetadata[$name]->getTarget()->unwrap() & $target) === 0 && $target) {
670 2
            throw AnnotationException::semanticalError(
671 2
                sprintf('Annotation @%s is not allowed to be declared on %s. You may only use this annotation on these code elements: %s.',
672 2
                     $originalName, $this->context, $this->annotationMetadata[$name]->getTarget()->describe())
673 2
            );
674 2
        }
675
676
        $values = $this->MethodCall();
677 322
678 96
        // checks all declared attributes for enums
679 96
        foreach ($this->annotationMetadata[$name]->getProperties() as $property) {
680 1
            $propertyName = $property->getName();
681 96
            $enum         = $property->getEnum();
682 284
683 284
            // checks if the attribute is a valid enumerator
684 284
            if ($enum !== null && isset($values[$propertyName]) && ! in_array($values[$propertyName], $enum['value'])) {
685
                throw AnnotationException::enumeratorError($propertyName, $name, $this->context, $enum['literal'], $values[$propertyName]);
686 45
            }
687 45
        }
688 272
689 182
        // checks all declared attributes
690
        foreach ($this->annotationMetadata[$name]->getProperties() as $property) {
691
            $propertyName = $property->getName();
692 323
            $valueName    = $propertyName;
693 102
            $type         = $property->getType();
694 98
695
            if ($property->isDefault() && !isset($values[$propertyName]) && isset($values['value'])) {
696
                $valueName = 'value';
697 4
            }
698
699
            // handle a not given attribute or null value
700
            if (! isset($values[$valueName])) {
701 297
                if ($property->isRequired()) {
702
                    throw AnnotationException::requiredError($propertyName, $originalName, $this->context, 'a(n) ' . $type['value']);
703 297
                }
704
705
                continue;
706
            }
707
708
            if ($type !== null && $type['type'] === 'array') {
709
                // handle the case of a single value
710
                if ( ! is_array($values[$valueName])) {
711
                    $values[$valueName] = [$values[$valueName]];
712
                }
713 297
714 41
                // checks if the attribute has array type declaration, such as "array<string>"
715
                if (isset($type['array_type'])) {
716
                    foreach ($values[$valueName] as $item) {
717
                        if (gettype($item) !== $type['array_type'] && !$item instanceof $type['array_type']) {
718 297
                            throw AnnotationException::attributeTypeError($propertyName, $originalName, $this->context, 'either a(n) '.$type['array_type'].', or an array of '.$type['array_type'].'s', $item);
719 5
                        }
720 2
                    }
721
                }
722
            } elseif ($type !== null && gettype($values[$valueName]) !== $type['type'] && !$values[$valueName] instanceof $type['type']) {
723 3
                throw AnnotationException::attributeTypeError($propertyName, $originalName, $this->context, 'a(n) '.$type['value'], $values[$valueName]);
724
            }
725
        }
726
727 292
        // check if the annotation expects values via the constructor,
728
        // or directly injected into public properties
729
        if ($this->annotationMetadata[$name]->usesConstructor()) {
730 292
            return new $name($values);
731
        }
732
733 292
        $instance = new $name();
734 9
735 9
        foreach ($values as $property => $value) {
736 9
            if (! isset($this->annotationMetadata[$name]->getProperties()[$property])) {
737
                if ('value' !== $property) {
738
                    throw AnnotationException::creationError(
739
                        sprintf(
740 284
                            'The annotation @%s declared on %s does not have a property named "%s". Available properties: %s',
741
                            $originalName,
742 267
                            $this->context,
743
                            $property,
744 4
                            implode(', ', array_keys($this->annotationMetadata[$name]->getProperties()))
745
                        )
746 4
                    );
747 4
                }
748
749
                $defaultProperty = $this->annotationMetadata[$name]->getDefaultProperty();
750
751
                // handle the case if the property has no annotations
752
                if ($defaultProperty === null) {
753 266
                    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 190
                }
755 190
756 7
                $property = $defaultProperty->getName();
757
            }
758
759
            $instance->{$property} = $value;
760 190
        }
761 168
762 2
        return $instance;
763
    }
764
765 166
    /**
766
     * MethodCall ::= ["(" [Values] ")"]
767
     *
768 177
     * @return array
769
     */
770 63
    private function MethodCall()
771 29
    {
772
        $values = [];
773
774
        if ( ! $this->lexer->isNextToken(DocLexer::T_OPEN_PARENTHESIS)) {
775 63
            return $values;
776 63
        }
777 59
778 36
        $this->match(DocLexer::T_OPEN_PARENTHESIS);
779
780
        if ( ! $this->lexer->isNextToken(DocLexer::T_CLOSE_PARENTHESIS)) {
781
            $values = $this->Values();
782 118
        }
783 74
784
        $this->match(DocLexer::T_CLOSE_PARENTHESIS);
785
786
        return $values;
787
    }
788
789 170
    /**
790 83
     * Values ::= Array | Value {"," Value}* [","]
791
     *
792
     * @return array
793 107
     */
794
    private function Values()
795 107
    {
796 75
        $values = [$this->Value()];
797 20
798 1
        while ($this->lexer->isNextToken(DocLexer::T_COMMA)) {
799
            $this->match(DocLexer::T_COMMA);
800
801
            if ($this->lexer->isNextToken(DocLexer::T_CLOSE_PARENTHESIS)) {
802 19
                break;
803 2
            }
804
805
            $token = $this->lexer->lookahead;
806
            $value = $this->Value();
807 72
808
            if ( ! is_object($value) && ! is_array($value)) {
809
                $this->syntaxError('Value', $token);
810 104
            }
811
812
            $values[] = $value;
813
        }
814
815
        foreach ($values as $k => $value) {
816
            if (is_object($value) && $value instanceof \stdClass) {
817
                $values[$value->name] = $value->value;
818 284
            } else if ( ! isset($values['value'])){
819
                $values['value'] = $value;
820 284
            } else {
821
                if ( ! is_array($values['value'])) {
822 284
                    $values['value'] = [$values['value']];
823 62
                }
824
825
                $values['value'][] = $value;
826 265
            }
827
828 265
            unset($values[$k]);
829 265
        }
830
831
        return $values;
832 248
    }
833
834 248
    /**
835
     * Constant ::= integer | string | float | boolean
836
     *
837
     * @return mixed
838
     *
839
     * @throws AnnotationException
840
     */
841
    private function Constant()
842 265
    {
843
        $identifier = $this->Identifier();
844 265
845
        if ( ! defined($identifier) && false !== strpos($identifier, '::') && '\\' !== $identifier[0]) {
846 248
            list($className, $const) = explode('::', $identifier);
847 15
848
            $pos = strpos($className, '\\');
849 15
            $alias = (false === $pos) ? $className : substr($className, 0, $pos);
850 2
            $found = false;
851
            $loweredAlias = strtolower($alias);
852
853 13
            switch (true) {
854 13
                case !empty ($this->namespaces):
855
                    foreach ($this->namespaces as $ns) {
856 13
                        if (class_exists($ns.'\\'.$className) || interface_exists($ns.'\\'.$className)) {
857
                             $className = $ns.'\\'.$className;
858
                             $found = true;
859
                             break;
860 13
                        }
861
                    }
862
                    break;
863 248
864 248
                case isset($this->imports[$loweredAlias]):
865 204
                    $found     = true;
866 60
                    $className = (false !== $pos)
867 60
                        ? $this->imports[$loweredAlias] . substr($className, $pos)
868
                        : $this->imports[$loweredAlias];
869 1
                    break;
870 1
871
                default:
872
                    if(isset($this->imports['__NAMESPACE__'])) {
873 1
                        $ns = $this->imports['__NAMESPACE__'];
874
875
                        if (class_exists($ns.'\\'.$className) || interface_exists($ns.'\\'.$className)) {
876 248
                            $className = $ns.'\\'.$className;
877
                            $found = true;
878
                        }
879 248
                    }
880
                    break;
881
            }
882
883
            if ($found) {
884
                 $identifier = $className . '::' . $const;
885
            }
886
        }
887
888
        // checks if identifier ends with ::class, \strlen('::class') === 7
889 75
        $classPos = stripos($identifier, '::class');
890
        if ($classPos === strlen($identifier) - 7) {
891 75
            return substr($identifier, 0, $classPos);
892
        }
893 75
894 17
        if (!defined($identifier)) {
895
            throw AnnotationException::semanticalErrorConstants($identifier, $this->context);
896 17
        }
897 17
898 17
        return constant($identifier);
899 17
    }
900
901
    /**
902 17
     * Identifier ::= string
903
     *
904
     * @return string
905
     */
906
    private function Identifier()
907
    {
908
        // check if we have an annotation
909
        if ( ! $this->lexer->isNextTokenAny(self::$classIdentifiers)) {
910
            $this->syntaxError('namespace separator or identifier');
911
        }
912 17
913 15
        $this->lexer->moveNext();
914 15
915
        $className = $this->lexer->token['value'];
916 15
917 15
        while ($this->lexer->lookahead['position'] === ($this->lexer->token['position'] + strlen($this->lexer->token['value']))
918
                && $this->lexer->isNextToken(DocLexer::T_NAMESPACE_SEPARATOR)) {
919
920 2
            $this->match(DocLexer::T_NAMESPACE_SEPARATOR);
921
            $this->matchAny(self::$classIdentifiers);
922
923
            $className .= '\\' . $this->lexer->token['value'];
924
        }
925
926
        return $className;
927
    }
928 2
929
    /**
930
     * Value ::= PlainValue | FieldAssignment
931 17
     *
932 15
     * @return mixed
933
     */
934
    private function Value()
935
    {
936
        $peek = $this->lexer->glimpse();
937 75
938 75
        if (DocLexer::T_EQUALS === $peek['type']) {
939 4
            return $this->FieldAssignment();
940
        }
941
942 71
        return $this->PlainValue();
943 1
    }
944
945
    /**
946 70
     * PlainValue ::= integer | string | float | boolean | Array | Annotation
947
     *
948
     * @return mixed
949
     */
950
    private function PlainValue()
951
    {
952
        if ($this->lexer->isNextToken(DocLexer::T_OPEN_CURLY_BRACES)) {
953
            return $this->Arrayx();
954 328
        }
955
956
        if ($this->lexer->isNextToken(DocLexer::T_AT)) {
957 328
            return $this->Annotation();
958 14
        }
959
960
        if ($this->lexer->isNextToken(DocLexer::T_IDENTIFIER)) {
961 328
            return $this->Constant();
962
        }
963 328
964
        switch ($this->lexer->lookahead['type']) {
965 328
            case DocLexer::T_STRING:
966 328
                $this->match(DocLexer::T_STRING);
967
                return $this->lexer->token['value'];
968 1
969 1
            case DocLexer::T_INTEGER:
970
                $this->match(DocLexer::T_INTEGER);
971
                return (int)$this->lexer->token['value'];
972
973
            case DocLexer::T_FLOAT:
974 327
                $this->match(DocLexer::T_FLOAT);
975
                return (float)$this->lexer->token['value'];
976
977
            case DocLexer::T_TRUE:
978
                $this->match(DocLexer::T_TRUE);
979
                return true;
980
981
            case DocLexer::T_FALSE:
982 265
                $this->match(DocLexer::T_FALSE);
983
                return false;
984 265
985
            case DocLexer::T_NULL:
986 265
                $this->match(DocLexer::T_NULL);
987 206
                return null;
988
989
            default:
990 132
                $this->syntaxError('PlainValue');
991
        }
992
    }
993
994
    /**
995
     * FieldAssignment ::= FieldName "=" PlainValue
996
     * FieldName ::= identifier
997
     *
998 265
     * @return \stdClass
999
     */
1000 265
    private function FieldAssignment()
1001 79
    {
1002
        $this->match(DocLexer::T_IDENTIFIER);
1003
        $fieldName = $this->lexer->token['value'];
1004 264
1005 55
        $this->match(DocLexer::T_EQUALS);
1006
1007
        $item = new \stdClass();
1008 228
        $item->name  = $fieldName;
1009 75
        $item->value = $this->PlainValue();
1010
1011
        return $item;
1012 161
    }
1013 161
1014 88
    /**
1015 88
     * Array ::= "{" ArrayEntry {"," ArrayEntry}* [","] "}"
1016
     *
1017 84
     * @return array
1018 56
     */
1019 56
    private function Arrayx()
1020
    {
1021 30
        $array = $values = [];
1022 28
1023 28
        $this->match(DocLexer::T_OPEN_CURLY_BRACES);
1024
1025 2
        // If the array is empty, stop parsing and return.
1026
        if ($this->lexer->isNextToken(DocLexer::T_CLOSE_CURLY_BRACES)) {
1027
            $this->match(DocLexer::T_CLOSE_CURLY_BRACES);
1028
1029 2
            return $array;
1030
        }
1031
1032
        $values[] = $this->ArrayEntry();
1033 2
1034
        while ($this->lexer->isNextToken(DocLexer::T_COMMA)) {
1035
            $this->match(DocLexer::T_COMMA);
1036
1037
            // optional trailing comma
1038 2
            if ($this->lexer->isNextToken(DocLexer::T_CLOSE_CURLY_BRACES)) {
1039
                break;
1040
            }
1041
1042
            $values[] = $this->ArrayEntry();
1043
        }
1044
1045
        $this->match(DocLexer::T_CLOSE_CURLY_BRACES);
1046
1047
        foreach ($values as $value) {
1048 206
            list ($key, $val) = $value;
1049
1050 206
            if ($key !== null) {
1051 206
                $array[$key] = $val;
1052
            } else {
1053 206
                $array[] = $val;
1054
            }
1055 206
        }
1056 206
1057 206
        return $array;
1058
    }
1059 204
1060
    /**
1061
     * ArrayEntry ::= Value | KeyValuePair
1062
     * KeyValuePair ::= Key ("=" | ":") PlainValue | Constant
1063
     * Key ::= string | integer | Constant
1064
     *
1065
     * @return array
1066
     */
1067 79
    private function ArrayEntry()
1068
    {
1069 79
        $peek = $this->lexer->glimpse();
1070
1071 79
        if (DocLexer::T_EQUALS === $peek['type']
1072
                || DocLexer::T_COLON === $peek['type']) {
1073
1074 79
            if ($this->lexer->isNextToken(DocLexer::T_IDENTIFIER)) {
1075 1
                $key = $this->Constant();
1076
            } else {
1077 1
                $this->matchAny([DocLexer::T_INTEGER, DocLexer::T_STRING]);
1078
                $key = $this->lexer->token['value'];
1079
            }
1080 79
1081
            $this->matchAny([DocLexer::T_EQUALS, DocLexer::T_COLON]);
1082 79
1083 54
            return [$key, $this->PlainValue()];
1084
        }
1085
1086 54
        return [null, $this->Value()];
1087 4
    }
1088
1089
    /**
1090 54
     * Checks whether the given $name matches any ignored annotation name or namespace
1091
     *
1092
     * @param string $name
1093 79
     *
1094
     * @return bool
1095 79
     */
1096 79
    private function isIgnoredAnnotation($name)
1097
    {
1098 79
        if ($this->ignoreNotImportedAnnotations || isset($this->ignoredAnnotationNames[$name])) {
1099 13
            return true;
1100
        }
1101 70
1102
        foreach (array_keys($this->ignoredAnnotationNamespaces) as $ignoredAnnotationNamespace) {
1103
            $ignoredAnnotationNamespace = rtrim($ignoredAnnotationNamespace, '\\') . '\\';
1104
1105 79
            if (0 === stripos(rtrim($name, '\\') . '\\', $ignoredAnnotationNamespace)) {
1106
                return true;
1107
            }
1108
        }
1109
1110
        return false;
1111
    }
1112
}
1113