Failed Conditions
Push — master ( ecccd5...ae55c7 )
by Marco
33s
created

DocParser::Annotation()   F

Complexity

Conditions 47
Paths 8688

Size

Total Lines 190
Code Lines 98

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 97
CRAP Score 47.0023

Importance

Changes 0
Metric Value
eloc 98
dl 0
loc 190
ccs 97
cts 98
cp 0.9898
rs 0
c 0
b 0
f 0
cc 47
nc 8688
nop 0
crap 47.0023

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

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

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

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

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

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

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

469
            $attribute->type     = (false !== strpos($propertyComment, '@var') && preg_match('/@var\s+([^\s]+)/',/** @scrutinizer ignore-type */ $propertyComment, $matches))
Loading history...
470 114
                ? $matches[1]
471
                : 'mixed';
472
473 114
            $this->collectAttributeTypeMetadata($propertyBuilder, $attribute);
474
475
            // checks if the property has @Enum
476 114
            if (false !== strpos($propertyComment, '@Enum')) {
477 5
                $context = 'property ' . $class->name . "::\$" . $property->name;
478
479 5
                self::$metadataParser->setTarget(Target::TARGET_PROPERTY);
480
481 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

481
                foreach (self::$metadataParser->parse(/** @scrutinizer ignore-type */ $propertyComment, $context) as $annotation) {
Loading history...
482 3
                    if ( ! $annotation instanceof Enum) {
483
                        continue;
484
                    }
485
486 3
                    $propertyBuilder->withEnum($this->createEnumType($annotation->value));
487
                }
488
            }
489
490 112
            $annotationBuilder->withProperty($propertyBuilder->build());
491
        }
492
493 182
        $this->metadata->add($annotationBuilder->build());
494 182
    }
495
496
    /**
497
     * @param (string|int|float|bool)[] $values
498
     */
499 3
    private function createEnumType(array $values) : Type
500
    {
501
        $types = array_map(static function ($value) : Type {
502 3
            if (is_string($value)) {
503 2
                return new ConstantStringType($value);
504
            }
505 1
            if (is_int($value)) {
506 1
                return new ConstantIntegerType($value);
507
            }
508
            if (is_float($value)) {
509
                return new ConstantFloatType($value);
510
            }
511
            if (is_bool($value)) {
512
                return new ConstantBooleanType($value);
513
            }
0 ignored issues
show
Bug Best Practice introduced by
The function implicitly returns null when the if condition on line 511 is false. This is incompatible with the type-hinted return Doctrine\Annotations\Type\Type. Consider adding a return statement or allowing null as return value.

For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example:

interface ReturnsInt {
    public function returnsIntHinted(): int;
}

class MyClass implements ReturnsInt {
    public function returnsIntHinted(): int
    {
        if (foo()) {
            return 123;
        }
        // here: null is implicitly returned
    }
}
Loading history...
514 3
        }, $values);
515
516 3
        if (count($types) === 1) {
517
            return array_values($types)[0];
518
        }
519
520 3
        return new UnionType(...$types);
521
    }
522
523
    /**
524
     * Collects parsing metadata for a given attribute.
525
     */
526 198
    private function collectAttributeTypeMetadata(
527
        PropertyMetadataBuilder $metadata,
528
        Attribute $attribute
529
    ) : void {
530 198
        $type = $attribute->type;
531
532
        // handle the case if the property type is mixed
533 198
        if ('mixed' === $type) {
534 193
            return;
535
        }
536
537 174
        if ($attribute->required) {
538 4
            $metadata->withBeingRequired();
539
        }
540
541
        // Evaluate type
542
543
        // Checks if the property has array<type>
544 174
        if (false !== $pos = strpos($type, '<')) {
545 169
            $arrayType = substr($type, $pos + 1, -1);
546
547 169
            $metadata->withType(new ArrayType(new MixedType(), $this->createTypeFromName($arrayType)));
548
549 169
            return;
550
        }
551
552
        // Checks if the property has type[]
553 174
         if (false !== $pos = strrpos($type, '[')) {
554 169
            $arrayType = substr($type, 0, $pos);
555
556 169
            $metadata->withType(new ArrayType(new MixedType(), $this->createTypeFromName($arrayType)));
557
558 169
            return;
559
        }
560
561 174
        $metadata->withType($this->createTypeFromName($attribute->type));
562 174
    }
563
564 174
    private function createTypeFromName(string $name) : Type
565
    {
566
        // allow uppercase Boolean in honor of George Boole
567 174
        if ($name === 'bool' || $name === 'boolean' || $name === 'Boolean') {
568 169
            return new BooleanType();
569
        }
570 174
        if ($name === 'int' || $name === 'integer') {
571 169
            return new IntegerType();
572
        }
573 174
        if ($name === 'float' || $name === 'double') {
574 169
            return new FloatType();
575
        }
576 174
        if ($name === 'string') {
577 174
            return new StringType();
578
        }
579 171
        if ($name === 'array') {
580 169
            return new ArrayType(new MixedType(), new MixedType());
581
        }
582 171
        if ($name === 'object') {
583
            return new ObjectType(null);
584
        }
585
586 171
        return new ObjectType($name);
587
    }
588
589
    /**
590
     * Annotations ::= Annotation {[ "*" ]* [Annotation]}*
591
     *
592
     * @return array
593
     */
594 293
    private function Annotations()
595
    {
596 293
        $annotations = [];
597
598 293
        while (null !== $this->lexer->lookahead) {
599 293
            if (DocLexer::T_AT !== $this->lexer->lookahead['type']) {
600 37
                $this->lexer->moveNext();
601 37
                continue;
602
            }
603
604
            // make sure the @ is preceded by non-catchable pattern
605 293
            if (null !== $this->lexer->token && $this->lexer->lookahead['position'] === $this->lexer->token['position'] + strlen($this->lexer->token['value'])) {
606 8
                $this->lexer->moveNext();
607 8
                continue;
608
            }
609
610
            // make sure the @ is followed by either a namespace separator, or
611
            // an identifier token
612 293
            if ((null === $peek = $this->lexer->glimpse())
613 293
                || (DocLexer::T_NAMESPACE_SEPARATOR !== $peek['type'] && !in_array($peek['type'], self::$classIdentifiers, true))
614 293
                || $peek['position'] !== $this->lexer->lookahead['position'] + 1) {
615 1
                $this->lexer->moveNext();
616 1
                continue;
617
            }
618
619 293
            $this->isNestedAnnotation = false;
620 293
            if (false !== $annot = $this->Annotation()) {
621 244
                $annotations[] = $annot;
622
            }
623
        }
624
625 287
        return $annotations;
626
    }
627
628
    /**
629
     * Annotation     ::= "@" AnnotationName MethodCall
630
     * AnnotationName ::= QualifiedName | SimpleName
631
     * QualifiedName  ::= NameSpacePart "\" {NameSpacePart "\"}* SimpleName
632
     * NameSpacePart  ::= identifier | null | false | true
633
     * SimpleName     ::= identifier | null | false | true
634
     *
635
     * @return mixed False if it is not a valid annotation.
636
     *
637
     * @throws AnnotationException
638
     */
639 293
    private function Annotation()
640
    {
641 293
        $this->match(DocLexer::T_AT);
642
643
        // check if we have an annotation
644 293
        $name = $this->Identifier();
645
646 292
        if ($this->lexer->isNextToken(DocLexer::T_MINUS)
647 292
            && $this->lexer->nextTokenIsAdjacent()
648
        ) {
649
            // Annotations with dashes, such as "@foo-" or "@foo-bar", are to be discarded
650 3
            return false;
651
        }
652
653
        // only process names which are not fully qualified, yet
654
        // fully qualified names must start with a \
655 290
        $originalName = $name;
656
657 290
        if ('\\' !== $name[0]) {
658 288
            $pos = strpos($name, '\\');
659 288
            $alias = (false === $pos)? $name : substr($name, 0, $pos);
660 288
            $found = false;
661 288
            $loweredAlias = strtolower($alias);
662
663 288
            if ($this->namespaces) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->namespaces of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

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