-
-
Notifications
You must be signed in to change notification settings - Fork 70
/
Container.php
390 lines (305 loc) 路 10.1 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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Nette\DI;
use Nette;
/**
* The dependency injection container default implementation.
*/
class Container
{
/**
* @var mixed[]
* @deprecated use Container::getParameter() or getParameters()
*/
public $parameters = [];
/** @var string[] service name => type */
protected array $types = [];
/** @var string[] alias => service name */
protected array $aliases = [];
/** @var array[] tag name => service name => tag value */
protected array $tags = [];
/** @var array[] type => (high, low, no) => services */
protected array $wiring = [];
/** @var object[] service name => instance */
private array $instances = [];
/** @var array<string, true> circular reference detector */
private array $creating;
/** @var array<string, int> */
private array $methods;
/** @var array<string, \Closure> service name => \Closure */
private array $factories = [];
public function __construct(array $params = [])
{
$this->parameters = $params + $this->getStaticParameters();
$this->methods = array_flip(get_class_methods($this));
}
public function getParameters(): array
{
return $this->parameters;
}
public function getParameter(string|int $key): mixed
{
if (!array_key_exists($key, $this->parameters)) {
$this->parameters[$key] = $this->preventDeadLock("%$key%", fn() => $this->getDynamicParameter($key));
}
return $this->parameters[$key];
}
protected function getStaticParameters(): array
{
return [];
}
protected function getDynamicParameter(string|int $key): mixed
{
throw new Nette\InvalidStateException(sprintf("Parameter '%s' not found. Check if 'di聽鈥郝爀xport聽鈥郝爌arameters' is enabled.", $key));
}
/**
* Adds the service or its factory to the container.
* @param object $service service or its factory
*/
public function addService(string $name, object $service): static
{
$name = $this->aliases[$name] ?? $name;
if (isset($this->instances[$name])) {
throw new Nette\InvalidStateException(sprintf("Service '%s' already exists.", $name));
}
if ($service instanceof \Closure) {
$rt = Nette\Utils\Type::fromReflection(new \ReflectionFunction($service));
$type = $rt ? Helpers::ensureClassType($rt, 'return type of closure') : '';
} else {
$type = $service::class;
}
if (!isset($this->methods[self::getMethodName($name)])) {
$this->types[$name] = $type;
} elseif (($expectedType = $this->getServiceType($name)) && !is_a($type, $expectedType, allow_string: true)) {
throw new Nette\InvalidArgumentException(sprintf(
"Service '%s' must be instance of %s, %s.",
$name,
$expectedType,
$type ? "$type given" : 'add typehint to closure',
));
}
if ($service instanceof \Closure) {
$this->factories[$name] = $service;
$this->types[$name] = $type;
} else {
$this->instances[$name] = $service;
}
return $this;
}
/**
* Removes a service instance from the container.
*/
public function removeService(string $name): void
{
$name = $this->aliases[$name] ?? $name;
unset($this->instances[$name]);
}
/**
* Returns the service instance. If it has not been created yet, it creates it.
* @throws MissingServiceException
*/
public function getService(string $name): object
{
if (!isset($this->instances[$name])) {
if (isset($this->aliases[$name])) {
return $this->getService($this->aliases[$name]);
}
$this->instances[$name] = $this->createService($name);
}
return $this->instances[$name];
}
/**
* Returns the service instance. If it has not been created yet, it creates it.
* Alias for getService().
* @throws MissingServiceException
*/
public function getByName(string $name): object
{
return $this->getService($name);
}
/**
* Returns type of the service.
* @throws MissingServiceException
*/
public function getServiceType(string $name): string
{
$method = self::getMethodName($name);
if (isset($this->aliases[$name])) {
return $this->getServiceType($this->aliases[$name]);
} elseif (isset($this->types[$name])) {
return $this->types[$name];
} elseif (isset($this->methods[$method])) {
return (string) (new \ReflectionMethod($this, $method))->getReturnType();
} elseif ($cb = $this->factories[$name] ?? null) {
return (string) (new \ReflectionFunction($cb))->getReturnType();
} else {
throw new MissingServiceException(sprintf("Service '%s' not found.", $name));
}
}
/**
* Does the service exist?
*/
public function hasService(string $name): bool
{
$name = $this->aliases[$name] ?? $name;
return isset($this->methods[self::getMethodName($name)]) || isset($this->instances[$name]) || isset($this->factories[$name]);
}
/**
* Has a service instance been created?
*/
public function isCreated(string $name): bool
{
if (!$this->hasService($name)) {
throw new MissingServiceException(sprintf("Service '%s' not found.", $name));
}
$name = $this->aliases[$name] ?? $name;
return isset($this->instances[$name]);
}
/**
* Creates new instance of the service.
* @throws MissingServiceException
*/
public function createService(string $name): object
{
$name = $this->aliases[$name] ?? $name;
$method = self::getMethodName($name);
if ($callback = ($this->factories[$name] ?? null)) {
$service = $this->preventDeadLock($name, fn() => $callback());
} elseif (isset($this->methods[$method])) {
$service = $this->preventDeadLock($name, fn() => $this->$method());
} else {
throw new MissingServiceException(sprintf("Service '%s' not found.", $name));
}
if (!is_object($service)) {
throw new Nette\UnexpectedValueException(sprintf(
"Unable to create service '$name', value returned by %s is not object.",
$callback instanceof \Closure ? 'closure' : "method $method()",
));
}
return $service;
}
/**
* Returns an instance of the autowired service of the given type. If it has not been created yet, it creates it.
* @template T of object
* @param class-string<T> $type
* @return ($throw is true ? T : ?T)
* @throws MissingServiceException
*/
public function getByType(string $type, bool $throw = true): ?object
{
$type = Helpers::normalizeClass($type);
if (!empty($this->wiring[$type][0])) {
if (count($names = $this->wiring[$type][0]) === 1) {
return $this->getService($names[0]);
}
natsort($names);
throw new MissingServiceException(sprintf("Multiple services of type $type found: %s.", implode(', ', $names)));
} elseif ($throw) {
if (!class_exists($type) && !interface_exists($type)) {
throw new MissingServiceException(sprintf("Service of type '%s' not found. Check the class name because it cannot be found.", $type));
} elseif ($this->findByType($type)) {
throw new MissingServiceException(sprintf("Service of type %s is not autowired or is missing in di\u{a0}鈥篭u{a0}export\u{a0}鈥篭u{a0}types.", $type));
} else {
throw new MissingServiceException(sprintf('Service of type %s not found. Did you add it to configuration file?', $type));
}
}
return null;
}
/**
* Returns the names of autowired services of the given type.
* @return string[]
* @internal
*/
public function findAutowired(string $type): array
{
$type = Helpers::normalizeClass($type);
return array_merge($this->wiring[$type][0] ?? [], $this->wiring[$type][1] ?? []);
}
/**
* Returns the names of all services of the given type.
* @return string[]
*/
public function findByType(string $type): array
{
$type = Helpers::normalizeClass($type);
return empty($this->wiring[$type])
? []
: array_merge(...array_values($this->wiring[$type]));
}
/**
* Returns the names of services with the given tag.
* @return array of [service name => tag attributes]
*/
public function findByTag(string $tag): array
{
return $this->tags[$tag] ?? [];
}
/**
* Prevents circular references during service creation by checking if the service is already being created.
*/
private function preventDeadLock(string $key, \Closure $callback): mixed
{
if (isset($this->creating[$key])) {
throw new Nette\InvalidStateException(sprintf('Circular reference detected for: %s.', implode(', ', array_keys($this->creating))));
}
try {
$this->creating[$key] = true;
return $callback();
} finally {
unset($this->creating[$key]);
}
}
/********************* autowiring ****************d*g**/
/**
* Creates an instance of the class and passes dependencies to the constructor using autowiring.
*/
public function createInstance(string $class, array $args = []): object
{
$rc = new \ReflectionClass($class);
if (!$rc->isInstantiable()) {
throw new ServiceCreationException(sprintf('Class %s is not instantiable.', $class));
} elseif ($constructor = $rc->getConstructor()) {
return $rc->newInstanceArgs($this->autowireArguments($constructor, $args));
} elseif ($args) {
throw new ServiceCreationException(sprintf('Unable to pass arguments, class %s has no constructor.', $class));
}
return new $class;
}
/**
* Calls all methods starting with 'inject' and passes dependencies to them via autowiring.
*/
public function callInjects(object $service): void
{
Extensions\InjectExtension::callInjects($this, $service);
}
/**
* Calls the method and passes dependencies to it via autowiring.
*/
public function callMethod(callable $function, array $args = []): mixed
{
return $function(...$this->autowireArguments(Nette\Utils\Callback::toReflection($function), $args));
}
private function autowireArguments(\ReflectionFunctionAbstract $function, array $args = []): array
{
return Resolver::autowireArguments($function, $args, fn(string $type, bool $single) => $single
? $this->getByType($type)
: array_map($this->getService(...), $this->findAutowired($type)));
}
/**
* Returns the method name for creating a service.
*/
final public static function getMethodName(string $name): string
{
if ($name === '') {
throw new Nette\InvalidArgumentException('Service name must be a non-empty string.');
}
return 'createService' . str_replace('.', '__', ucfirst($name));
}
public function initialize(): void
{
}
}