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 Reflection; |
11
|
|
|
use ReflectionClass; |
12
|
|
|
use ReflectionMethod; |
13
|
|
|
|
14
|
|
|
use function version_compare; |
15
|
|
|
|
16
|
|
|
use const PHP_VERSION; |
17
|
|
|
use const PHP_VERSION_ID; |
18
|
|
|
|
19
|
|
|
final class AnnotatedClassMethods |
20
|
|
|
{ |
21
|
|
|
/** @var Reader */ |
22
|
|
|
private $reader; |
23
|
|
|
|
24
|
|
|
/** @var NameKeyVarString */ |
25
|
|
|
private $nameKeyVarString; |
26
|
|
|
|
27
|
|
|
public function __construct(Reader $reader) |
28
|
|
|
{ |
29
|
|
|
$this->reader = $reader; |
30
|
|
|
$this->nameKeyVarString = new NameKeyVarString($reader); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @phpstan-param ReflectionClass<object> $class |
35
|
|
|
*/ |
36
|
|
|
public function getConstructorName(ReflectionClass $class): Name |
37
|
|
|
{ |
38
|
|
|
$constructor = $class->getConstructor(); |
39
|
|
|
if (! $constructor) { |
40
|
|
|
return new Name(Name::ANY); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
if (PHP_VERSION_ID >= 80000) { |
44
|
|
|
$name = Name::withAttributes(new ReflectionMethod($class->getName(), '__construct')); |
|
|
|
|
45
|
|
|
if ($name) { |
46
|
|
|
return $name; |
47
|
|
|
} |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
$named = $this->reader->getMethodAnnotation($constructor, Named::class); |
51
|
|
|
if ($named instanceof Named) { |
52
|
|
|
/** @var Named $named */ |
53
|
|
|
return new Name($named->value); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
$name = ($this->nameKeyVarString)($constructor); |
57
|
|
|
if ($name !== null) { |
58
|
|
|
return new Name($name); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
return new Name(Name::ANY); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* @return ?SetterMethod |
|
|
|
|
66
|
|
|
*/ |
67
|
|
|
public function getSetterMethod(ReflectionMethod $method) |
68
|
|
|
{ |
69
|
|
|
$inject = $this->reader->getMethodAnnotation($method, InjectInterface::class); |
70
|
|
|
if (! $inject instanceof InjectInterface) { |
71
|
|
|
return null; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
$name = $this->getName($method); |
75
|
|
|
$setterMethod = new SetterMethod($method, $name); |
76
|
|
|
if ($inject->isOptional()) { |
77
|
|
|
$setterMethod->setOptional(); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
return $setterMethod; |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
private function getName(ReflectionMethod $method): Name |
84
|
|
|
{ |
85
|
|
|
if (PHP_VERSION_ID >= 80000) { |
86
|
|
|
$name = Name::withAttributes($method); |
87
|
|
|
if ($name) { |
88
|
|
|
return $name; |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|
92
|
|
|
$nameValue = ($this->nameKeyVarString)($method); |
93
|
|
|
|
94
|
|
|
return new Name($nameValue); |
95
|
|
|
} |
96
|
|
|
} |
97
|
|
|
|