Failed Conditions
Pull Request — master (#256)
by Michael
02:33
created

DocParser::createTypeFromName()   B

Complexity

Conditions 11
Paths 7

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 11.044

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 22
ccs 13
cts 14
cp 0.9286
rs 7.3166
c 0
b 0
f 0
cc 11
nc 7
nop 1
crap 11.044

How to fix   Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
namespace Doctrine\Annotations;
4
5
use Doctrine\Annotations\Annotation\Attribute;
6
use Doctrine\Annotations\Metadata\AnnotationTarget;
7
use Doctrine\Annotations\Metadata\Builder\AnnotationMetadataBuilder;
8
use Doctrine\Annotations\Metadata\Builder\PropertyMetadataBuilder;
9
use Doctrine\Annotations\Metadata\InternalAnnotations;
10
use Doctrine\Annotations\Metadata\MetadataCollection;
11
use Doctrine\Annotations\Metadata\TransientMetadataCollection;
12
use Doctrine\Annotations\Type\ArrayType;
13
use Doctrine\Annotations\Type\BooleanType;
14
use Doctrine\Annotations\Type\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 290
    public function __construct()
160
    {
161 290
        $this->lexer    = new DocLexer;
162 290
        $this->metadata = InternalAnnotations::createMetadata();
163 290
    }
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 47
    public function setIgnoredAnnotationNames(array $names)
176
    {
177 47
        $this->ignoredAnnotationNames = $names;
178 47
    }
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 58
    public function setIgnoredAnnotationNamespaces($ignoredAnnotationNamespaces)
188
    {
189 58
        $this->ignoredAnnotationNamespaces = $ignoredAnnotationNamespaces;
190 58
    }
191
192
    /**
193
     * Sets ignore on not-imported annotations.
194
     *
195
     * @param boolean $bool
196
     *
197
     * @return void
198
     */
199 270
    public function setIgnoreNotImportedAnnotations($bool)
200
    {
201 270
        $this->ignoreNotImportedAnnotations = (boolean) $bool;
202 270
    }
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 269
    public function setImports(array $imports)
232
    {
233 269
        if ($this->namespaces) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->namespaces of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
234
            throw new \RuntimeException('You must either use addNamespace(), or setImports(), but not both.');
235
        }
236
237 269
        $this->imports = $imports;
238 269
    }
239
240
    /**
241
     * Sets current target context as bitmask.
242
     *
243
     * @param integer $target
244
     *
245
     * @return void
246
     */
247 271
    public function setTarget($target)
248
    {
249 271
        $this->target = $target;
250 271
    }
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 290
    public function parse($input, $context = '')
261
    {
262 290
        $pos = $this->findInitialTokenPosition($input);
263 290
        if ($pos === null) {
264 19
            return [];
265
        }
266
267 289
        $this->context = $context;
268
269 289
        $this->lexer->setInput(trim(substr($input, $pos), '* /'));
270 289
        $this->lexer->moveNext();
271
272 289
        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 290
    private function findInitialTokenPosition($input)
283
    {
284 290
        $pos = 0;
285
286
        // search for first valid annotation
287 290
        while (($pos = strpos($input, '@', $pos)) !== false) {
288 290
            $preceding = substr($input, $pos - 1, 1);
289
290
            // if the @ is preceded by a space, a tab or * it is valid
291 290
            if ($pos === 0 || $preceding === ' ' || $preceding === '*' || $preceding === "\t") {
292 289
                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 289
    private function match($token)
310
    {
311 289
        if ( ! $this->lexer->isNextToken($token) ) {
312
            $this->syntaxError($this->lexer->getLiteral($token));
313
        }
314
315 289
        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 11
    private function syntaxError($expected, $token = null)
348
    {
349 11
        if ($token === null) {
350 11
            $token = $this->lexer->lookahead;
351
        }
352
353 11
        $message  = sprintf('Expected %s, got ', $expected);
354 11
        $message .= ($this->lexer->lookahead === null)
355
            ? 'end of string'
356 11
            : sprintf("'%s' at position %s", $token['value'], $token['position']);
357
358 11
        if (strlen($this->context)) {
359 8
            $message .= ' in ' . $this->context;
360
        }
361
362 11
        $message .= '.';
363
364 11
        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 284
    private function classExists($fqcn)
375
    {
376 284
        if (isset($this->classExists[$fqcn])) {
377 240
            return $this->classExists[$fqcn];
378
        }
379
380
        // final check, does this class exist?
381 284
        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 263
    private function collectAnnotationMetadata($name)
392
    {
393 263
        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 263
        $class      = new ReflectionClass($name);
407 263
        $docComment = $class->getDocComment();
408
409
        // verify that the class is really meant to be an annotation
410 263
        if (strpos($docComment, '@Annotation') === false) {
411 4
            $this->nonAnnotationClasses[$name] = true;
412 4
            return;
413
        }
414
415 259
        $constructor       = $class->getConstructor();
416 259
        $useConstructor    = $constructor !== null && $constructor->getNumberOfParameters() > 0;
417 259
        $annotationBuilder = new AnnotationMetadataBuilder($name);
418
419 259
        if ($useConstructor) {
420 89
            $annotationBuilder->withUsingConstructor();
421
        }
422
423 259
        self::$metadataParser->setTarget(Target::TARGET_CLASS);
424
425 259
        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 253
        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 182
        foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $i => $property) {
452 168
            $propertyBuilder = new PropertyMetadataBuilder($property->getName());
453 168
            $propertyComment = $property->getDocComment();
454
455 168
            if ($i === 0) {
456 168
                $propertyBuilder->withBeingDefault();
457
            }
458
459
460 168
            if ($propertyComment === false) {
461 73
                $annotationBuilder->withProperty($propertyBuilder->build());
462
463 73
                continue;
464
            }
465
466 113
            $attribute           = new Attribute();
467 113
            $attribute->required = (false !== strpos($propertyComment, '@Required'));
0 ignored issues
show
Bug introduced by
It seems like $propertyComment can also be of type true; however, parameter $haystack of strpos() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

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

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

469
            $attribute->type     = (false !== strpos($propertyComment, '@var') && preg_match('/@var\s+([^\s]+)/',/** @scrutinizer ignore-type */ $propertyComment, $matches))
Loading history...
470 113
                ? $matches[1]
471
                : 'mixed';
472
473 113
            $this->collectAttributeTypeMetadata($propertyBuilder, $attribute);
474
475
            // checks if the property has @Enum
476 113
            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 111
            $annotationBuilder->withProperty($propertyBuilder->build());
491
        }
492
493 180
        $this->metadata->add($annotationBuilder->build());
494 180
    }
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
     * @param array     $metadata
527
     * @param Attribute $attribute
528
     */
529 197
    private function collectAttributeTypeMetadata(
530
        PropertyMetadataBuilder $metadata,
531
        Attribute $attribute
532
    ) : void {
533 197
        $type = $attribute->type;
534
535
        // handle the case if the property type is mixed
536 197
        if ($type === 'mixed') {
537 193
            return;
538
        }
539
540 173
        if ($attribute->required) {
541 3
            $metadata->withBeingRequired();
542
        }
543
544
        // Evaluate type
545
546
        // Checks if the property has array<type>
547 173
        if (false !== $pos = strpos($type, '<')) {
548 169
            $arrayType = substr($type, $pos + 1, -1);
549
550 169
            $metadata->withType(new ArrayType(new MixedType(), $this->createTypeFromName($arrayType)));
551
552 169
            return;
553
        }
554
555
        // Checks if the property has type[]
556 173
         if (false !== $pos = strrpos($type, '[')) {
557 169
            $arrayType = substr($type, 0, $pos);
558
559 169
            $metadata->withType(new ArrayType(new MixedType(), $this->createTypeFromName($arrayType)));
560
561 169
            return;
562
        }
563
564 173
        $metadata->withType($this->createTypeFromName($attribute->type));
565 173
    }
566
567 173
    private function createTypeFromName(string $name) : Type
568
    {
569 173
        if ($name === 'bool' || $name === 'boolean' || $name === 'Boolean') {
570 169
            return new BooleanType();
571
        }
572 173
        if ($name === 'int' || $name === 'integer') {
573 169
            return new IntegerType();
574
        }
575 173
        if ($name === 'float' || $name === 'double') {
576 169
            return new FloatType();
577
        }
578 173
        if ($name === 'string') {
579 173
            return new StringType();
580
        }
581 171
        if ($name === 'array') {
582 169
            return new ArrayType(new MixedType(), new MixedType());
583
        }
584 171
        if ($name === 'object') {
585
            return new ObjectType(null);
586
        }
587
588 171
        return new ObjectType($name);
589
    }
590
591
    /**
592
     * Annotations ::= Annotation {[ "*" ]* [Annotation]}*
593
     *
594
     * @return array
595
     */
596 289
    private function Annotations()
597
    {
598 289
        $annotations = [];
599
600 289
        while (null !== $this->lexer->lookahead) {
601 289
            if (DocLexer::T_AT !== $this->lexer->lookahead['type']) {
602 33
                $this->lexer->moveNext();
603 33
                continue;
604
            }
605
606
            // make sure the @ is preceded by non-catchable pattern
607 289
            if (null !== $this->lexer->token && $this->lexer->lookahead['position'] === $this->lexer->token['position'] + strlen($this->lexer->token['value'])) {
608 7
                $this->lexer->moveNext();
609 7
                continue;
610
            }
611
612
            // make sure the @ is followed by either a namespace separator, or
613
            // an identifier token
614 289
            if ((null === $peek = $this->lexer->glimpse())
615 289
                || (DocLexer::T_NAMESPACE_SEPARATOR !== $peek['type'] && !in_array($peek['type'], self::$classIdentifiers, true))
616 289
                || $peek['position'] !== $this->lexer->lookahead['position'] + 1) {
617 1
                $this->lexer->moveNext();
618 1
                continue;
619
            }
620
621 289
            $this->isNestedAnnotation = false;
622 289
            if (false !== $annot = $this->Annotation()) {
623 243
                $annotations[] = $annot;
624
            }
625
        }
626
627 283
        return $annotations;
628
    }
629
630
    /**
631
     * Annotation     ::= "@" AnnotationName MethodCall
632
     * AnnotationName ::= QualifiedName | SimpleName
633
     * QualifiedName  ::= NameSpacePart "\" {NameSpacePart "\"}* SimpleName
634
     * NameSpacePart  ::= identifier | null | false | true
635
     * SimpleName     ::= identifier | null | false | true
636
     *
637
     * @return mixed False if it is not a valid annotation.
638
     *
639
     * @throws AnnotationException
640
     */
641 289
    private function Annotation()
642
    {
643 289
        $this->match(DocLexer::T_AT);
644
645
        // check if we have an annotation
646 289
        $name = $this->Identifier();
647
648
        // only process names which are not fully qualified, yet
649
        // fully qualified names must start with a \
650 288
        $originalName = $name;
651
652 288
        if ('\\' !== $name[0]) {
653 286
            $pos = strpos($name, '\\');
654 286
            $alias = (false === $pos)? $name : substr($name, 0, $pos);
655 286
            $found = false;
656 286
            $loweredAlias = strtolower($alias);
657
658 286
            if ($this->namespaces) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->namespaces of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

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