Failed Conditions
Push — type ( c389f1...fc7bda )
by Michael
02:26
created

DocParser::PlainValue()   B

Complexity

Conditions 10
Paths 10

Size

Total Lines 41
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 11.097

Importance

Changes 0
Metric Value
eloc 27
dl 0
loc 41
ccs 21
cts 27
cp 0.7778
rs 7.6666
c 0
b 0
f 0
cc 10
nc 10
nop 0
crap 11.097

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

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

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

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