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