1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Cekta\DI; |
6
|
|
|
|
7
|
|
|
use ReflectionClass; |
8
|
|
|
use ReflectionException; |
9
|
|
|
use ReflectionMethod; |
10
|
|
|
|
11
|
|
|
class Reflection |
12
|
|
|
{ |
13
|
|
|
private $instantiable = []; |
14
|
|
|
private $dependencies = []; |
15
|
|
|
private $variadic = []; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @param string $name |
19
|
|
|
* @return array<string> |
20
|
|
|
* @internal |
21
|
|
|
*/ |
22
|
12 |
|
public function getDependencies(string $name): array |
23
|
|
|
{ |
24
|
12 |
|
if (!array_key_exists($name, $this->dependencies)) { |
25
|
9 |
|
$this->load($name); |
26
|
|
|
} |
27
|
12 |
|
return $this->dependencies[$name]; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @param string $name |
32
|
|
|
* @return bool |
33
|
|
|
* @internal |
34
|
|
|
*/ |
35
|
6 |
|
public function isVariadic(string $name): bool |
36
|
|
|
{ |
37
|
6 |
|
if (!array_key_exists($name, $this->variadic)) { |
38
|
3 |
|
$this->load($name); |
39
|
|
|
} |
40
|
6 |
|
return $this->variadic[$name]; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @param string $name |
45
|
|
|
* @return bool |
46
|
|
|
* @internal |
47
|
|
|
*/ |
48
|
6 |
|
public function isInstantiable(string $name): bool |
49
|
|
|
{ |
50
|
6 |
|
if (!array_key_exists($name, $this->instantiable)) { |
51
|
6 |
|
$this->load($name); |
52
|
|
|
} |
53
|
6 |
|
return $this->instantiable[$name]; |
54
|
|
|
} |
55
|
|
|
|
56
|
18 |
|
private function load(string $name): void |
57
|
|
|
{ |
58
|
|
|
try { |
59
|
18 |
|
$class = new ReflectionClass($name); |
60
|
15 |
|
$this->instantiable[$name] = $class->isInstantiable(); |
61
|
15 |
|
$params = self::getMethodParameters($class->getConstructor()); |
62
|
15 |
|
$this->variadic[$name] = $params[0]; |
63
|
15 |
|
$this->dependencies[$name] = $params[1]; |
64
|
3 |
|
} catch (ReflectionException $exception) { |
65
|
3 |
|
$this->dependencies[$name] = []; |
66
|
3 |
|
$this->instantiable[$name] = false; |
67
|
3 |
|
$this->variadic[$name] = false; |
68
|
|
|
} |
69
|
18 |
|
} |
70
|
|
|
|
71
|
15 |
|
private static function getMethodParameters(?ReflectionMethod $method): array |
72
|
|
|
{ |
73
|
15 |
|
$variadic = false; |
74
|
15 |
|
$parameters = []; |
75
|
15 |
|
if ($method !== null) { |
76
|
12 |
|
foreach ($method->getParameters() as $parameter) { |
77
|
12 |
|
$variadic = $parameter->isVariadic(); |
78
|
12 |
|
$class = $parameter->getClass(); |
79
|
12 |
|
$parameters[] = $class && $variadic !== true ? $class->name : $parameter->name; |
80
|
|
|
} |
81
|
|
|
} |
82
|
15 |
|
return [$variadic, $parameters]; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|