Passed
Push — error-message ( b7292a...ff40fa )
by Akihito
04:28 queued 02:25
created

AnnotatedClassMethods::getConstructorName()   A

Complexity

Conditions 6
Paths 8

Size

Total Lines 26
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
dl 0
loc 26
c 1
b 0
f 0
rs 9.2222
cc 6
nc 8
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ray\Di;
6
7
use Doctrine\Common\Annotations\Reader;
8
use Ray\Di\Di\InjectInterface;
9
use Ray\Di\Di\Named;
10
use ReflectionClass;
11
use ReflectionMethod;
12
13
use const PHP_VERSION_ID;
14
15
final class AnnotatedClassMethods
16
{
17
    /** @var Reader */
18
    private $reader;
19
20
    /** @var NameKeyVarString */
21
    private $nameKeyVarString;
22
23
    public function __construct(Reader $reader)
24
    {
25
        $this->reader = $reader;
26
        $this->nameKeyVarString = new NameKeyVarString($reader);
27
    }
28
29
    /**
30
     * @phpstan-param ReflectionClass<object> $class
31
     */
32
    public function getConstructorName(ReflectionClass $class): Name
33
    {
34
        $constructor = $class->getConstructor();
35
        if (! $constructor) {
36
            return new Name(Name::ANY);
37
        }
38
39
        if (PHP_VERSION_ID >= 80000) {
40
            $name = Name::withAttributes(new ReflectionMethod($class->getName(), '__construct'));
41
            if ($name) {
42
                return $name;
43
            }
44
        }
45
46
        $named = $this->reader->getMethodAnnotation($constructor, Named::class);
47
        if ($named instanceof Named) {
48
            /** @var Named $named */
49
            return new Name($named->value);
50
        }
51
52
        $name = ($this->nameKeyVarString)($constructor);
53
        if ($name !== null) {
54
            return new Name($name);
55
        }
56
57
        return new Name(Name::ANY);
58
    }
59
60
    public function getSetterMethod(ReflectionMethod $method): ?SetterMethod
61
    {
62
        $inject = $this->reader->getMethodAnnotation($method, InjectInterface::class);
63
        if (! $inject instanceof InjectInterface) {
64
            return null;
65
        }
66
67
        $name = $this->getName($method);
68
        $setterMethod = new SetterMethod($method, $name);
69
        if ($inject->isOptional()) {
70
            $setterMethod->setOptional();
71
        }
72
73
        return $setterMethod;
74
    }
75
76
    private function getName(ReflectionMethod $method): Name
77
    {
78
        if (PHP_VERSION_ID >= 80000) {
79
            $name = Name::withAttributes($method);
80
            if ($name) {
81
                return $name;
82
            }
83
        }
84
85
        $nameValue = ($this->nameKeyVarString)($method);
86
87
        return new Name($nameValue);
88
    }
89
}
90