1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Antidot\Container; |
6
|
|
|
|
7
|
|
|
use Psr\Container\ContainerInterface; |
8
|
|
|
use ReflectionMethod; |
9
|
|
|
|
10
|
|
|
class ContainerBuilder |
11
|
|
|
{ |
12
|
7 |
|
private function __construct() |
13
|
|
|
{ |
14
|
7 |
|
} |
15
|
|
|
|
16
|
7 |
|
public static function build(array $dependencies, bool $autowire = false): ContainerInterface |
17
|
|
|
{ |
18
|
7 |
|
$self = new self(); |
19
|
|
|
|
20
|
7 |
|
return new Container( |
21
|
7 |
|
$self->parseConfigFor($dependencies), |
22
|
7 |
|
$autowire |
23
|
|
|
); |
24
|
|
|
} |
25
|
|
|
|
26
|
7 |
|
private function parseConfigFor(array $dependencies): ContainerConfig |
27
|
|
|
{ |
28
|
|
|
$containerConfig = [ |
29
|
7 |
|
'config' => $dependencies, |
30
|
|
|
'parameters' => [], |
31
|
|
|
]; |
32
|
7 |
|
if (isset($dependencies['dependencies']['delegators'])) { |
33
|
|
|
$containerConfig['delegators'] = $dependencies['dependencies']['delegators']; |
34
|
|
|
} |
35
|
7 |
|
foreach ($dependencies['dependencies']['invokables'] ?? [] as $name => $invokable) { |
36
|
2 |
|
$containerConfig[$name] = $invokable; |
37
|
|
|
} |
38
|
7 |
|
foreach ($dependencies['dependencies']['aliases'] ?? [] as $name => $service) { |
39
|
1 |
|
$containerConfig[$name] = $service; |
40
|
|
|
} |
41
|
7 |
|
foreach ($dependencies['dependencies']['factories'] ?? [] as $name => $factory) { |
42
|
|
|
$containerConfig[$name] = static function (ContainerInterface $container) use ($factory) { |
43
|
3 |
|
if (is_array($factory)) { |
44
|
1 |
|
$class = array_shift($factory); |
45
|
1 |
|
$instance = new $class(); |
46
|
1 |
|
$method = new ReflectionMethod($class, '__invoke'); |
47
|
1 |
|
return $method->invokeArgs($instance, array_merge([$container], $factory)); |
48
|
|
|
} |
49
|
|
|
|
50
|
2 |
|
if (is_callable($factory)) { |
51
|
1 |
|
return $factory($container); |
52
|
|
|
} |
53
|
|
|
|
54
|
1 |
|
if (class_exists($factory)) { |
55
|
1 |
|
return (new $factory())($container); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
throw new \InvalidArgumentException('Invalid factory type given.'); |
59
|
3 |
|
}; |
60
|
|
|
} |
61
|
|
|
|
62
|
7 |
|
foreach ($dependencies['dependencies']['conditionals'] ?? [] as $name => $conditional) { |
63
|
1 |
|
$containerConfig['parameters'][$name] = $conditional['arguments']; |
64
|
1 |
|
$containerConfig[$name] = $conditional['class']; |
65
|
|
|
} |
66
|
|
|
|
67
|
7 |
|
return new ContainerConfig($containerConfig); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|