1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace HexMakina\LeMarchand; |
4
|
|
|
|
5
|
|
|
class ReflectionFactory |
6
|
|
|
{ |
7
|
|
|
public static function make($class, $construction_args = [], $container) |
8
|
|
|
{ |
9
|
|
|
try { |
10
|
|
|
$rc = new \ReflectionClass($class); |
11
|
|
|
$instance = null; |
12
|
|
|
|
13
|
|
|
if (!is_null($constructor = $rc->getConstructor())) { |
14
|
|
|
$instance = self::makeWithContructorArgs($rc, $construction_args, $container); |
15
|
|
|
} else { |
16
|
|
|
$instance = $rc->newInstanceArgs(); |
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
if ($rc->hasMethod('set_container')) { |
20
|
|
|
$instance->set_container($container); |
21
|
|
|
} |
22
|
|
|
return $instance; |
23
|
|
|
} catch (\ReflectionException $e) { |
24
|
|
|
throw new ContainerException($e->getMessage()); |
25
|
|
|
} |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
private static function makeWithContructorArgs(\ReflectionClass $rc, $construction_args, $container) |
29
|
|
|
{ |
30
|
|
|
$constructor = $rc->getConstructor(); |
31
|
|
|
$construction_args = self::getConstructorParameters($constructor, $construction_args, $container); |
32
|
|
|
|
33
|
|
|
$instance = null; |
34
|
|
|
if ($constructor->isPrivate()) { // singleton ? |
35
|
|
|
// first argument is the static instance-making method |
36
|
|
|
$singleton_method = $rc->getMethod(array_shift($construction_args)); |
37
|
|
|
// invoke the method with remaining constructor args |
38
|
|
|
$instance = $container->resolved($rc->getName(), $singleton_method->invoke(null, $construction_args)); |
39
|
|
|
} else { |
40
|
|
|
$instance = $rc->newInstanceArgs($construction_args); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
return $instance; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
private static function getConstructorParameters(\ReflectionMethod $constructor, $construction_args = [], $container) |
47
|
|
|
{ |
48
|
|
|
if (empty($construction_args)) { |
49
|
|
|
foreach ($constructor->getParameters() as $param) { |
50
|
|
|
if ($param->getType()) { |
51
|
|
|
$construction_args [] = $container->get($param->getType()->getName()); |
|
|
|
|
52
|
|
|
} else { |
53
|
|
|
$setting = 'settings.Constructor.' . $constructor->class . '.' . $param->getName(); |
54
|
|
|
$construction_args [] = $container->getSettings($setting); |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
return $construction_args; |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|