1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace TomPHP\ConfigServiceProvider\Pimple; |
4
|
|
|
|
5
|
|
|
use Pimple\Container; |
6
|
|
|
use ReflectionClass; |
7
|
|
|
use TomPHP\ConfigServiceProvider\ApplicationConfig; |
8
|
|
|
use TomPHP\ConfigServiceProvider\Configurator as ConfiguratorInterface; |
9
|
|
|
use TomPHP\ConfigServiceProvider\Exception\UnsupportedFeatureException; |
10
|
|
|
use TomPHP\ConfigServiceProvider\InflectorConfig; |
11
|
|
|
use TomPHP\ConfigServiceProvider\ServiceConfig; |
12
|
|
|
use TomPHP\ConfigServiceProvider\ServiceDefinition; |
13
|
|
|
|
14
|
|
|
final class Configurator implements ConfiguratorInterface |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @var Container |
18
|
|
|
*/ |
19
|
|
|
private $container; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @param Container $container |
23
|
|
|
*/ |
24
|
|
|
public function setContainer($container) |
25
|
|
|
{ |
26
|
|
|
$this->container = $container; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function addApplicationConfig(ApplicationConfig $config, $prefix = 'config') |
30
|
|
|
{ |
31
|
|
|
if (!empty($prefix)) { |
32
|
|
|
$prefix .= $config->getSeparator(); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
foreach ($config as $key => $value) { |
36
|
|
|
$this->container[$prefix . $key] = $value; |
37
|
|
|
} |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
public function addServiceConfig(ServiceConfig $config) |
41
|
|
|
{ |
42
|
|
|
foreach ($config as $definition) { |
43
|
|
|
$this->addServiceToContainer($definition); |
44
|
|
|
} |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
public function addInflectorConfig(InflectorConfig $config) |
48
|
|
|
{ |
49
|
|
|
throw UnsupportedFeatureException::forInflectors('Pimple'); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
private function addServiceToContainer(ServiceDefinition $definition) |
53
|
|
|
{ |
54
|
|
|
$factory = function () use ($definition) { |
55
|
|
|
$reflection = new ReflectionClass($definition->getClass()); |
56
|
|
|
|
57
|
|
|
$instance = $reflection->newInstanceArgs($this->resolveArguments($definition->getArguments())); |
58
|
|
|
|
59
|
|
|
foreach ($definition->getMethods() as $name => $args) { |
60
|
|
|
call_user_func_array([$instance, $name], $this->resolveArguments($args)); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
return $instance; |
64
|
|
|
}; |
65
|
|
|
|
66
|
|
|
if (!$definition->isSingleton()) { |
67
|
|
|
$factory = $this->container->factory($factory); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
$this->container[$definition->getName()] = $factory; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
private function resolveArguments(array $arguments) |
74
|
|
|
{ |
75
|
|
|
return array_map( |
76
|
|
|
function ($argument) { |
77
|
|
|
if (isset($this->container[$argument])) { |
78
|
|
|
return $this->container[$argument]; |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
return $argument; |
82
|
|
|
}, |
83
|
|
|
$arguments |
84
|
|
|
); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|