Passed
Push — master ( 7b52e4...d40832 )
by Jakub
01:50
created

PhpAttributesEngine::getReflection()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 5
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 10
c 1
b 0
f 1
cc 4
nc 2
nop 2
crap 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace MyTester\Annotations;
6
7
use MyTester\Attributes\BaseAttribute;
8
use Nette\Utils\Strings;
9
use ReflectionClass;
10
use ReflectionException;
11
use ReflectionMethod;
12
13
/**
14
 * Php attributes engine for annotations reader
15
 *
16
 * @author Jakub Konečný
17
 * @internal
18
 */
19
final class PhpAttributesEngine implements \MyTester\IAnnotationsReaderEngine
20
{
21 1
    public function hasAnnotation(string $name, string|object $class, string $method = null): bool
22
    {
23 1
        return count($this->getReflection($class, $method)->getAttributes($this->getClassName($name))) > 0;
24
    }
25
26 1
    public function getAnnotation(string $name, string|object $class, string $method = null): mixed
27
    {
28 1
        $attributes = $this->getReflection($class, $method)->getAttributes($this->getClassName($name));
29 1
        if (count($attributes) === 0) {
30 1
            return null;
31
        }
32
        /** @var BaseAttribute $attribute */
33 1
        $attribute = $attributes[0]->newInstance();
34 1
        return $attribute->value;
35
    }
36
37 1
    private function getClassName(string $baseName): string
38
    {
39 1
        return "MyTester\\Attributes\\" . Strings::firstUpper($baseName);
40
    }
41
42
    /**
43
     * @throws ReflectionException
44
     */
45 1
    private function getReflection(string|object $class, string $method = null): ReflectionClass|ReflectionMethod
46
    {
47 1
        if ($method !== null) {
48 1
            $reflection = new ReflectionMethod(is_object($class) ? get_class($class) : $class, $method);
49
        } else {
50 1
            $reflection = new ReflectionClass(is_object($class) ? get_class($class) : $class);
51
        }
52 1
        return $reflection;
53
    }
54
}
55