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