1
|
|
|
<?php |
2
|
|
|
namespace UltraLite\Container; |
3
|
|
|
|
4
|
|
|
use Psr\Container\ContainerInterface; |
5
|
|
|
use UltraLite\Container\Exception\DiServiceNotFound; |
6
|
|
|
use Interop\Container\Exception\NotFoundException; |
7
|
|
|
|
8
|
|
|
class Container implements ContainerInterface |
9
|
|
|
{ |
10
|
|
|
/** @var \Closure[] */ |
11
|
|
|
private $serviceFactories = []; |
12
|
|
|
|
13
|
|
|
/** @var array */ |
14
|
|
|
private $services = []; |
15
|
|
|
|
16
|
|
|
/** @var ContainerInterface */ |
17
|
|
|
private $delegateContainer; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @param string $serviceId |
21
|
|
|
* @param \Closure $serviceFactory |
22
|
|
|
*/ |
23
|
|
|
public function set($serviceId, \Closure $serviceFactory) |
24
|
|
|
{ |
25
|
|
|
$this->serviceFactories[$serviceId] = $serviceFactory; |
26
|
|
|
unset($this->services[$serviceId]); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @param string $path |
31
|
|
|
*/ |
32
|
|
|
public function configureFromFile(string $path) |
33
|
|
|
{ |
34
|
|
|
foreach (require $path as $serviceId => $serviceFactory) { |
35
|
|
|
$this->set($serviceId, $serviceFactory); |
36
|
|
|
} |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @throws NotFoundException |
41
|
|
|
* |
42
|
|
|
* @param string $serviceId |
43
|
|
|
* @return mixed |
44
|
|
|
*/ |
45
|
|
|
public function get($serviceId) |
46
|
|
|
{ |
47
|
|
|
if (!$this->has($serviceId)) { |
48
|
|
|
throw DiServiceNotFound::createFromServiceId($serviceId); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
if (!isset($this->services[$serviceId])) { |
52
|
|
|
$this->services[$serviceId] = $this->getServiceFromFactory($serviceId); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
return $this->services[$serviceId]; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @return string[] |
60
|
|
|
*/ |
61
|
|
|
public function listServiceIds() : array |
62
|
|
|
{ |
63
|
|
|
return array_keys($this->serviceFactories); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* @return mixed |
68
|
|
|
*/ |
69
|
|
|
private function getServiceFromFactory(string $serviceId) |
70
|
|
|
{ |
71
|
|
|
$serviceFactory = $this->serviceFactories[$serviceId]; |
72
|
|
|
$containerToUseForDependencies = $this->delegateContainer ?: $this; |
73
|
|
|
return $serviceFactory($containerToUseForDependencies); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* @param string $serviceId |
78
|
|
|
* @return bool |
79
|
|
|
*/ |
80
|
|
|
public function has($serviceId) |
81
|
|
|
{ |
82
|
|
|
return isset($this->serviceFactories[$serviceId]); |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
public function setDelegateContainer(ContainerInterface $delegateContainer) |
86
|
|
|
{ |
87
|
|
|
$this->delegateContainer = $delegateContainer; |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|