-
Notifications
You must be signed in to change notification settings - Fork 1
/
ServiceContainer.php
137 lines (119 loc) · 3 KB
/
ServiceContainer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
<?php
namespace Coduo\TuTu;
/**
* Simple service container inspired by PhpSpec/ServiceContainer class which was created on top of Pimple.
*/
class ServiceContainer
{
/**
* @var array
*/
private $parameters = [];
/**
* @var array
*/
private $serviceDefinitions = [];
/**
* @var array
*/
private $tags = [];
/**
* @param $id
* @return bool
*/
public function hasParameter($id)
{
return array_key_exists($id, $this->parameters);
}
/**
* @param $id
* @param $value
*/
public function setParameter($id, $value)
{
$this->parameters[$id] = $value;
}
/**
* @param $id
* @return mixed
* @throws \RuntimeException
*/
public function getParameter($id)
{
if (!array_key_exists($id, $this->parameters)) {
throw new \RuntimeException(sprintf("Service container does not have parameter with id \"%s\"", $id));
}
return $this->parameters[$id];
}
/**
* @param $id
* @return bool
*/
public function hasService($id)
{
return array_key_exists($id, $this->serviceDefinitions);
}
public function removeService($id)
{
if ($this->hasService($id)){
unset($this->serviceDefinitions[$id]);
}
}
/**
* getService($id) will return result of $definition closure.
* Callback will be executed with $this (ServiceContainer) as a argument.
*
* @param $id
* @param callable $definition
* @param array $tags
*/
public function setDefinition($id, \Closure $definition, $tags = [])
{
$this->serviceDefinitions[$id] = $definition;
$this->tags[$id] = $tags;
}
/**
* Works just like setDefinition but getService($id) is going to return
* exactly same value every single time.
*
* @param $id
* @param callable $definition
* @param array $tags
*/
public function setStaticDefinition($id, \Closure $definition, $tags = [])
{
$this->setDefinition($id, function ($container) use ($definition) {
static $instance;
if (!isset($instance)) {
$instance = $definition($container);
}
return $instance;
}, $tags);
}
/**
* @param $id
* @return mixed
* @throws \RuntimeException
*/
public function getService($id)
{
if (!array_key_exists($id, $this->serviceDefinitions)) {
throw new \RuntimeException("Service container does not have service with id \"key\"");
}
return $this->serviceDefinitions[$id]($this);
}
/**
* @param $tag
* @return array
*/
public function getServicesByTag($tag)
{
$services = [];
foreach ($this->tags as $serviceId => $tags) {
if (in_array($tag, $tags, true)) {
$services[] = $this->getService($serviceId);
}
}
return $services;
}
}