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

PhpAttributesEngine   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 1
Metric Value
wmc 8
eloc 13
dl 0
loc 34
ccs 15
cts 15
cp 1
rs 10
c 3
b 0
f 1

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getReflection() 0 8 4
A hasAnnotation() 0 3 1
A getClassName() 0 3 1
A getAnnotation() 0 9 2
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