-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathContainer.php
353 lines (298 loc) · 8.72 KB
/
Container.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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
<?php
namespace Darya\Service;
use Closure;
use Darya\Service\Exceptions\ContainerException;
use Darya\Service\Exceptions\NotFoundException;
use InvalidArgumentException;
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;
use ReflectionFunction;
use ReflectionParameter;
use Darya\Service\Contracts\ContainerAware;
use Darya\Service\Contracts\Container as ContainerInterface;
/**
* Darya's service container.
*
* Service containers can be used to associate interfaces with implementations.
* They ease interchanging the components and dependencies of an application.
*
* TODO: ArrayAccess
* TODO: factory() method
*
* @author Chris Andrew <[email protected]>
*/
class Container implements ContainerInterface
{
/**
* Set of abstract service names as keys and implementations as values.
*
* @var array
*/
protected $services = [];
/**
* Set of aliases as keys and interfaces as values.
*
* @var array
*/
protected $aliases = [];
/**
* A delegate container to resolve services from.
*
* @var ContainerInterface
*/
protected $delegate;
/**
* Instantiate a service container.
*
* Registers the service container with itself, as well as registering any
* given services and aliases.
*
* @param array $services [optional] Initial set of services and/or aliases
*/
public function __construct(array $services = [])
{
$this->register([
'Darya\Service\Contracts\Container' => $this,
'Darya\Service\Container' => $this
]);
$this->register($services);
}
/**
* Dynamically resolve a service.
*
* @param string $abstract The abstract service name
* @return mixed The resolved service
* @throws ContainerException
*/
public function __get($abstract)
{
return $this->get($abstract);
}
/**
* Dynamically register a service.
*
* @param string $abstract The abstract service name
* @param mixed $service The concrete service
*/
public function __set($abstract, $service)
{
$this->register([$abstract => $service]);
}
public function has($abstract)
{
return isset($this->aliases[$abstract]) || isset($this->services[$abstract]);
}
public function raw($abstract)
{
if (isset($this->aliases[$abstract])) {
$abstract = $this->aliases[$abstract];
return $this->raw($abstract);
}
if (isset($this->services[$abstract])) {
return $this->services[$abstract];
}
if (isset($this->delegate)) {
return $this->delegate->raw($abstract);
}
throw new NotFoundException("Service '$abstract' not found");
}
public function get($abstract, array $arguments = [])
{
$concrete = $this->raw($abstract);
try {
if ($concrete instanceof Closure || is_callable($concrete)) {
return $this->call($concrete, $arguments ?: [$this]);
}
if (is_string($concrete)) {
if ($abstract !== $concrete && $this->has($concrete)) {
return $this->get($concrete, $arguments);
}
if (class_exists($concrete)) {
return $this->create($concrete, $arguments);
}
}
} catch (ContainerException $exception) {
throw new ContainerException(
"Error resolving service '$abstract'",
$exception->getCode(),
$exception
);
}
return $concrete;
}
public function set($abstract, $concrete)
{
$this->services[$abstract] = is_callable($concrete) ? $this->share($concrete) : $concrete;
}
public function alias($alias, $abstract)
{
$this->aliases[$alias] = $abstract;
}
public function register(array $services)
{
foreach ($services as $key => $value) {
if (is_string($value) && isset($this->services[$value])) {
$this->alias($key, $value);
} else {
$this->set($key, $value);
}
}
}
public function share($callable)
{
if (!is_callable($callable)) {
throw new InvalidArgumentException('Service is not callable');
}
$container = $this;
return function () use ($callable, $container) {
static $instance;
if ($instance === null) {
$instance = $container->call($callable, [$container]);
}
return $instance;
};
}
public function call($callable, array $arguments = [])
{
if (!is_callable($callable)) {
throw new ContainerException("Callable given is not callable");
}
$method = is_array($callable) && count($callable) > 1 && method_exists($callable[0], $callable[1]);
try {
if ($method) {
$reflection = new ReflectionMethod($callable[0], $callable[1]);
} else {
$reflection = new ReflectionFunction($callable);
}
$parameters = $reflection->getParameters();
$arguments = $this->resolveParameterArguments($parameters, $arguments);
} catch (ReflectionException $exception) {
throw new ContainerException(
"Error calling callable",
$exception->getCode(),
$exception
);
}
return $method ? $reflection->invokeArgs($callable[0], $arguments) : $reflection->invokeArgs($arguments);
}
public function create($class, array $arguments = [])
{
try {
$reflection = new ReflectionClass($class);
$constructor = $reflection->getConstructor();
if (!$constructor) {
return $reflection->newInstance();
}
$parameters = $constructor->getParameters();
$arguments = $this->resolveParameterArguments($parameters, $arguments);
} catch (ReflectionException $exception) {
throw new ContainerException(
"Error creating instance of '$class'",
$exception->getCode(),
$exception
);
}
$instance = $reflection->newInstanceArgs($arguments);
if ($instance instanceof ContainerAware) {
$instance->setServiceContainer($this);
}
return $instance;
}
/**
* Delegate a container to resolve services from when this container is
* unable to.
*
* @param ContainerInterface $container The container to delegate
*/
public function delegate(ContainerInterface $container)
{
$this->delegate = $container;
}
/**
* Merge resolved parameters arguments with the given arguments.
*
* TODO: Make this smarter.
*
* @param array $resolved The resolved arguments
* @param array $arguments The given arguments
* @return array The merged arguments
*/
protected function mergeResolvedParameterArguments(array $resolved, array $arguments = [])
{
if (empty(array_filter(array_keys($arguments), 'is_numeric'))) {
// We can perform a simple array merge if there are no numeric keys
return array_merge($resolved, $arguments);
}
// Otherwise, we use the given arguments, falling back to resolved arguments
// TODO: Some alternate merge involving numeric indexes, maybe?
return $arguments ?: $resolved;
}
/**
* Resolve arguments for a set of reflection parameters.
*
* @param ReflectionParameter[] $parameters The parameters to resolve arguments for
* @param array $arguments [optional] The given arguments
* @return array The resolved arguments keyed by parameter name
* @throws ContainerException
*/
protected function resolveParameterArguments(array $parameters, array $arguments = [])
{
$resolved = [];
foreach ($parameters as $index => $parameter) {
// TODO: Consider nullable parameters (array_keys_exists() vs isset())
if (isset($arguments[$index])) {
$resolved[$parameter->name] = $arguments[$index];
continue;
}
if (isset($arguments[$parameter->name])) {
$resolved[$parameter->name] = $arguments[$parameter->name];
continue;
}
$argument = $this->resolveParameterArgument($parameter);
$resolved[$parameter->name] = $argument;
}
$resolved = $this->mergeResolvedParameterArguments($resolved, $arguments);
return $resolved;
}
/**
* Resolve an argument for a reflection parameter.
*
* @param ReflectionParameter|null $parameter The parameter to resolve an argument for
* @return mixed The resolved argument for the parameter
* @throws ContainerException
*/
protected function resolveParameterArgument(ReflectionParameter $parameter)
{
$type = $this->resolveParameterType($parameter);
if ($type !== null) {
if ($this->has($type)) {
return $this->get($type);
}
if (class_exists($type)) {
return $this->create($type);
}
}
if ($parameter->isDefaultValueAvailable()) {
try {
return $parameter->getDefaultValue();
} catch (ReflectionException $exception) {
// We want to continue to the exception below
// when a default value cannot be resolved
}
}
// TODO: Include reflection exception as previous exception?
throw new ContainerException("Unresolvable parameter '\${$parameter->name}'");
}
/**
* Resolve the class type hint of a reflection parameter.
*
* @param ReflectionParameter $parameter The parameter to resolve class type hint for
* @return string|null The class type hint of the reflection parameter
*/
protected function resolveParameterType(ReflectionParameter $parameter)
{
$class = $parameter->getClass();
return is_object($class) ? $class->name : null;
}
}