Passed
Pull Request — master (#50)
by Daniel
08:24
created

AbstractHelper::initReader()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Component Bundle Project
5
 *
6
 * (c) Daniel West <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Silverback\ApiComponentBundle\Helper;
15
16
use Doctrine\Common\Annotations\Reader;
17
use Silverback\ApiComponentBundle\Exception\InvalidArgumentException;
18
use Silverback\ApiComponentBundle\Utility\ClassMetadataTrait;
19
20
abstract class AbstractHelper
21
{
22
    use ClassMetadataTrait;
23
24
    protected Reader $reader;
25
26
    abstract public function getConfiguration($class);
27
28
    /**
29
     * @param object|string $class
30
     */
31 9
    public function isConfigured($class): bool
32
    {
33
        try {
34 9
            $this->getConfiguration($class);
35 9
        } catch (InvalidArgumentException $e) {
36 9
            return false;
37
        }
38
39 9
        return true;
40
    }
41
42
    /**
43
     * @required
44
     */
45 9
    protected function initReader(Reader $reader): void
46
    {
47 9
        $this->reader = $reader;
48 9
    }
49
50
    /**
51
     * @param object|string $class
52
     *
53
     * @throws \ReflectionException
54
     */
55 9
    protected function getAnnotationConfiguration($class, string $annotationClass)
56
    {
57 9
        if (null === $class || (\is_string($class) && !class_exists($class))) {
58
            throw new InvalidArgumentException(sprintf('$class passed to %s must be a valid class FQN or object', __CLASS__));
59
        }
60
61 9
        $reflection = new \ReflectionClass($class);
62
        /** @var $annotationClass|null $annotation */
63
        while (
64 9
            !($annotation = $this->reader->getClassAnnotation($reflection, $annotationClass)) &&
65 9
            ($reflection = $reflection->getParentClass())
66
        ) {
67 9
            continue;
68
        }
69 9
        if (!$annotation) {
70 9
            throw new InvalidArgumentException(sprintf('%s does not have %s annotation', \is_object($class) ? \get_class($class) : $class, $annotationClass));
71
        }
72
73 9
        return $annotation;
74
    }
75
}
76