Reflector   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 19
c 1
b 0
f 0
dl 0
loc 56
rs 10
wmc 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getTypeHint() 0 17 5
A assertAttributesAvailable() 0 5 2
A attributesAvailable() 0 3 1
A getFirstAttribute() 0 9 2
1
<?php
2
declare(strict_types=1);
3
4
namespace Habemus\Autowiring;
5
6
use Habemus\Exception\ContainerException;
7
use Habemus\Utility\PHPVersion;
8
use ReflectionNamedType;
9
use ReflectionParameter;
10
use ReflectionProperty;
11
12
class Reflector
13
{
14
    /**
15
     * @param ReflectionParameter|ReflectionProperty $subject
16
     * @param bool $detectPrimitiveTypes
17
     * @return string|null
18
     */
19
    public function getTypeHint($subject, bool $detectPrimitiveTypes = true): ?string
20
    {
21
        $type = $subject->getType();
22
        if (! $type instanceof ReflectionNamedType) {
23
            return null;
24
        }
25
26
        if ($type->isBuiltin() && !$detectPrimitiveTypes) {
27
            return null;
28
        }
29
30
        $typeHint = ltrim($type->getName(), "?");
31
        if ($typeHint === 'self') {
32
            $typeHint = $subject->getDeclaringClass()->getName();
33
        }
34
35
        return $typeHint;
36
    }
37
38
    /**
39
     * @param ReflectionParameter|ReflectionProperty $subject
40
     * @param string $attribute
41
     * @return mixed
42
     * @throws ContainerException
43
     */
44
    public function getFirstAttribute($subject, string $attribute)
45
    {
46
        $this->assertAttributesAvailable();
47
        $attribute = $subject->getAttributes($attribute)[0] ?? null;
48
        if (empty($attribute)) {
49
            return null;
50
        }
51
52
        return $attribute->newInstance();
53
    }
54
55
    public function attributesAvailable(): bool
56
    {
57
        return PHPVersion::current() >= PHPVersion::V8_0;
58
    }
59
60
    /**
61
     * @throws ContainerException
62
     */
63
    public function assertAttributesAvailable(): void
64
    {
65
        if (!$this->attributesAvailable()) {
66
            throw new ContainerException(
67
                "Attributes injection are not available. Use a PHP version >=8.0."
68
            );
69
        }
70
    }
71
}
72