Passed
Push — main ( 6c9276...76dcd0 )
by Anatoly
06:53 queued 02:07
created

DoctrineAnnotationReader::default()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
eloc 7
c 0
b 0
f 0
dl 0
loc 12
ccs 0
cts 2
cp 0
rs 10
cc 2
nc 2
nop 0
crap 6
1
<?php
2
3
/**
4
 * It's free open-source software released under the MIT License.
5
 *
6
 * @author Anatoly Nekhay <[email protected]>
7
 * @copyright Copyright (c) 2021, Anatoly Nekhay
8
 * @license https://github.com/sunrise-php/hydrator/blob/master/LICENSE
9
 * @link https://github.com/sunrise-php/hydrator
10
 */
11
12
declare(strict_types=1);
13
14
namespace Sunrise\Hydrator\AnnotationReader;
15
16
use Doctrine\Common\Annotations\AnnotationReader;
17
use Doctrine\Common\Annotations\Reader;
18
use Generator;
19
use LogicException;
20
use ReflectionProperty;
21
use Sunrise\Hydrator\AnnotationReaderInterface;
22
23
use function class_exists;
24
use function sprintf;
25
26
/**
27
 * @link https://github.com/doctrine/annotations
28
 *
29
 * @since 3.1.0
30
 */
31
final class DoctrineAnnotationReader implements AnnotationReaderInterface
32
{
33
34
    /**
35
     * @var Reader
36
     */
37
    private Reader $reader;
38
39
    /**
40
     * Constructor of the class
41
     *
42
     * @param Reader $reader
43
     */
44
    public function __construct(Reader $reader)
45
    {
46
        $this->reader = $reader;
47
    }
48
49
    /**
50
     * Creates a new instance of the class with the doctrine's default annotation reader
51
     *
52
     * @return self
53
     *
54
     * @throws LogicException If the doctrine/annotations package isn't installed on the server.
55
     */
56
    public static function default(): self
57
    {
58
        // @codeCoverageIgnoreStart
59
        if (!class_exists(AnnotationReader::class)) {
60
            throw new LogicException(sprintf(
61
                'The annotation reader {%s} requires the doctrine/annotations package, ' .
62
                'run the command `composer require doctrine/annotations` to resolve it.',
63
                __CLASS__,
64
            ));
65
        } // @codeCoverageIgnoreEnd
66
67
        return new self(new AnnotationReader());
68
    }
69
70
    /**
71
     * @inheritDoc
72
     */
73
    public function getAnnotations(string $name, $holder): Generator
74
    {
75
        if ($holder instanceof ReflectionProperty) {
76
            $annotations = $this->reader->getPropertyAnnotations($holder);
77
            foreach ($annotations as $annotation) {
78
                if ($annotation instanceof $name) {
79
                    yield $annotation;
80
                }
81
            }
82
        }
83
    }
84
}
85