1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Laganica\Di\Resolver; |
4
|
|
|
|
5
|
|
|
use Laganica\Di\Exception\ClassNotFoundException; |
6
|
|
|
use PhpDocReader\AnnotationException; |
7
|
|
|
use PhpDocReader\PhpDocReader; |
8
|
|
|
use phpDocumentor\Reflection\DocBlockFactory; |
9
|
|
|
use ReflectionClass; |
10
|
|
|
use ReflectionException; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Class ReflectionResolver |
14
|
|
|
* |
15
|
|
|
* @package Laganica\Di\Resolver |
16
|
|
|
*/ |
17
|
|
|
abstract class ReflectionResolver extends Resolver |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* @param string $class |
21
|
|
|
* |
22
|
|
|
* @throws ClassNotFoundException |
23
|
|
|
* |
24
|
|
|
* @return array |
25
|
|
|
*/ |
26
|
12 |
|
protected function getConstructorParams(string $class): array |
27
|
|
|
{ |
28
|
12 |
|
$params = []; |
29
|
|
|
|
30
|
|
|
try { |
31
|
12 |
|
$reflection = new ReflectionClass($class); |
32
|
2 |
|
} catch (ReflectionException $e) { |
33
|
2 |
|
throw ClassNotFoundException::create($class); |
34
|
|
|
} |
35
|
|
|
|
36
|
10 |
|
$constructor = $reflection->getConstructor(); |
37
|
|
|
|
38
|
10 |
|
if ($constructor === null) { |
39
|
9 |
|
return $params; |
40
|
|
|
} |
41
|
|
|
|
42
|
4 |
|
foreach ($constructor->getParameters() AS $param) { |
43
|
4 |
|
$dependencyId = $param->getClass()->name; |
44
|
4 |
|
$params[] = $this->getContainer()->get($dependencyId); |
45
|
|
|
} |
46
|
|
|
|
47
|
3 |
|
return $params; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @param object $entry |
52
|
|
|
* |
53
|
|
|
* @throws ClassNotFoundException |
54
|
|
|
* |
55
|
|
|
* @return void |
56
|
|
|
*/ |
57
|
1 |
|
protected function injectProperties(object $entry): void |
58
|
|
|
{ |
59
|
1 |
|
$class = get_class($entry); |
60
|
|
|
|
61
|
|
|
try { |
62
|
1 |
|
$reflectionClass = new ReflectionClass($class); |
63
|
|
|
} catch (ReflectionException $e) { |
64
|
|
|
throw ClassNotFoundException::create($class); |
65
|
|
|
} |
66
|
|
|
|
67
|
1 |
|
$phpDocReader = new PhpDocReader(); |
68
|
1 |
|
$docBlockFactory = DocBlockFactory::createInstance(); |
69
|
|
|
|
70
|
1 |
|
foreach ($reflectionClass->getProperties() as $reflectionProperty) { |
71
|
1 |
|
if ($reflectionProperty->isStatic()) { |
72
|
|
|
continue; |
73
|
|
|
} |
74
|
|
|
|
75
|
1 |
|
$docBlock = $docBlockFactory->create($reflectionProperty->getDocComment()); |
76
|
|
|
|
77
|
1 |
|
if (!$docBlock->hasTag('Inject')) { |
78
|
1 |
|
continue; |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
try { |
82
|
1 |
|
$identifier = $phpDocReader->getPropertyClass($reflectionProperty); |
83
|
1 |
|
$reflectionProperty->setAccessible(true); |
84
|
1 |
|
$reflectionProperty->setValue($entry, $this->getContainer()->get($identifier)); |
85
|
|
|
} catch (AnnotationException $ex) { |
86
|
|
|
throw new ClassNotFoundException($ex->getMessage()); |
87
|
|
|
} |
88
|
|
|
} |
89
|
1 |
|
} |
90
|
|
|
} |
91
|
|
|
|