-
-
Notifications
You must be signed in to change notification settings - Fork 46
/
Container.php
501 lines (446 loc) · 15.4 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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
<?php
declare(strict_types=1);
namespace Yiisoft\Di;
use Closure;
use InvalidArgumentException;
use Psr\Container\ContainerInterface;
use Yiisoft\Definitions\ArrayDefinition;
use Yiisoft\Definitions\Exception\CircularReferenceException;
use Yiisoft\Definitions\Exception\InvalidConfigException;
use Yiisoft\Definitions\Exception\NotFoundException;
use Yiisoft\Definitions\Exception\NotInstantiableException;
use Yiisoft\Definitions\Infrastructure\DefinitionValidator;
use Yiisoft\Definitions\Infrastructure\DefinitionStorage;
use Yiisoft\Di\Contracts\ServiceProviderInterface;
use function array_key_exists;
use function array_keys;
use function get_class;
use function gettype;
use function implode;
use function in_array;
use function is_array;
use function is_object;
use function is_string;
/**
* Container implements a [dependency injection](http://en.wikipedia.org/wiki/Dependency_injection) container.
*/
final class Container implements ContainerInterface
{
private const META_TAGS = 'tags';
private const META_RESET = 'reset';
private const ALLOWED_META = [self::META_TAGS, self::META_RESET];
/**
* @var DefinitionStorage storage of object definitions
*/
private DefinitionStorage $definitions;
/**
* @var array used to collect ids instantiated during build
* to detect circular references
*/
private array $building = [];
/**
* @var bool $validate Validate definitions when set
*/
private bool $validate;
/**
* @var object[]
*/
private array $instances = [];
private CompositeContainer $delegates;
private array $tags;
private array $resetters = [];
/**
* Container constructor.
*
* @param array $definitions Definitions to put into container.
* @param array $providers Service providers to get definitions from.
* lookup to when resolving dependencies. If provided the current container
* is no longer queried for dependencies.
* @param array $tags
* @param bool $validate If definitions should be validated immediately.
* @param array $delegates Container delegates. Each delegate must is a callable in format
* "function (ContainerInterface $container): ContainerInterface". The container instance returned is used
* in case a service can not be found in primary container.
*
* @throws InvalidConfigException
*
* @psalm-suppress PropertyNotSetInConstructor
*/
public function __construct(
array $definitions = [],
array $providers = [],
array $tags = [],
bool $validate = true,
array $delegates = []
) {
$this->tags = $tags;
$this->validate = $validate;
$this->definitions = new DefinitionStorage();
$this->setDefaultDefinitions();
$this->setMultiple($definitions);
$this->addProviders($providers);
$this->setDelegates($delegates);
}
/**
* Returns a value indicating whether the container has the definition of the specified name.
*
* @param string $id class name, interface name or alias name
*
* @return bool whether the container is able to provide instance of class specified.
*
* @see set()
*/
public function has($id): bool
{
/** @psalm-suppress DocblockTypeContradiction */
if (!is_string($id)) {
return false;
}
if ($this->isTagAlias($id)) {
$tag = substr($id, 4);
return isset($this->tags[$tag]);
}
try {
return $this->definitions->has($id);
} catch (CircularReferenceException $e) {
return true;
}
}
/**
* Returns an instance by either interface name or alias.
*
* Same instance of the class will be returned each time this method is called.
*
* @param string $id The interface or an alias name that was previously registered.
*
* @throws CircularReferenceException
* @throws InvalidConfigException
* @throws NotFoundException
* @throws NotInstantiableException
*
* @return mixed|object An instance of the requested interface.
*
* @psalm-template T
* @psalm-param string|class-string<T> $id
* @psalm-return ($id is class-string ? T : mixed)
*/
public function get($id)
{
/** @psalm-suppress TypeDoesNotContainType */
if (!is_string($id)) {
throw new InvalidArgumentException("Id must be a string, {$this->getVariableType($id)} given.");
}
if (!array_key_exists($id, $this->instances)) {
try {
$this->instances[$id] = $this->build($id);
} catch (NotFoundException $e) {
if (!$this->delegates->has($id)) {
throw $e;
}
return $this->delegates->get($id);
}
}
if ($id === StateResetter::class && $this->definitions->get($id) === StateResetter::class) {
$resetters = [];
foreach ($this->resetters as $serviceId => $callback) {
if (isset($this->instances[$serviceId])) {
$resetters[$serviceId] = $callback;
}
}
if ($this->delegates->has(StateResetter::class)) {
$resetters[] = $this->delegates->get(StateResetter::class);
}
$this->instances[$id]->setResetters($resetters);
}
return $this->instances[$id];
}
/**
* Sets a definition to the container. Definition may be defined multiple ways.
*
* @param string $id
* @param mixed $definition
*
* @throws InvalidConfigException
*
* @see `DefinitionNormalizer::normalize()`
*/
private function set(string $id, $definition): void
{
[$definition, $meta] = DefinitionParser::parse($definition);
if ($this->validate) {
$this->validateDefinition($definition, $id);
$this->validateMeta($meta);
}
if (isset($meta[self::META_TAGS])) {
if ($this->validate) {
$this->validateTags($meta[self::META_TAGS]);
}
$this->setTags($id, $meta[self::META_TAGS]);
}
if (isset($meta[self::META_RESET])) {
$this->setResetter($id, $meta[self::META_RESET]);
}
unset($this->instances[$id]);
$this->definitions->set($id, $definition);
}
/**
* Sets multiple definitions at once.
*
* @param array $config definitions indexed by their ids
*
* @throws InvalidConfigException
*/
private function setMultiple(array $config): void
{
foreach ($config as $id => $definition) {
if ($this->validate && !is_string($id)) {
throw new InvalidConfigException(sprintf('Key must be a string. %s given.', $this->getVariableType($id)));
}
$this->set($id, $definition);
}
}
private function setDefaultDefinitions(): void
{
$this->setMultiple([
ContainerInterface::class => $this,
StateResetter::class => StateResetter::class,
]);
}
/**
* Set container delegates.
*
* Each delegate must is a callable in format "function (ContainerInterface $container): ContainerInterface".
* The container instance returned is used in case a service can not be found in primary container.
*
* @param array $delegates
*
* @throws InvalidConfigException
*/
private function setDelegates(array $delegates): void
{
$this->delegates = new CompositeContainer();
foreach ($delegates as $delegate) {
if (!$delegate instanceof Closure) {
throw new InvalidConfigException(
'Delegate must be callable in format "function (ContainerInterface $container): ContainerInterface".'
);
}
$delegate = $delegate($this);
if (!$delegate instanceof ContainerInterface) {
throw new InvalidConfigException(
'Delegate callable must return an object that implements ContainerInterface.'
);
}
$this->delegates->attach($delegate);
}
$this->definitions->setDelegateContainer($this->delegates);
}
/**
* @param mixed $definition
*
* @throws InvalidConfigException
*/
private function validateDefinition($definition, ?string $id = null): void
{
if (is_array($definition) && isset($definition[DefinitionParser::IS_PREPARED_ARRAY_DEFINITION_DATA])) {
$class = $definition['class'];
$constructorArguments = $definition['__construct()'];
$methodsAndProperties = $definition['methodsAndProperties'];
$definition = array_merge(
$class === null ? [] : [ArrayDefinition::CLASS_NAME => $class],
[ArrayDefinition::CONSTRUCTOR => $constructorArguments],
$methodsAndProperties,
);
}
if ($definition instanceof ExtensibleService) {
throw new InvalidConfigException('Invalid definition. ExtensibleService is only allowed in provider extensions.');
}
DefinitionValidator::validate($definition, $id);
}
/**
* @throws InvalidConfigException
*/
private function validateMeta(array $meta): void
{
foreach ($meta as $key => $_value) {
if (!in_array($key, self::ALLOWED_META, true)) {
throw new InvalidConfigException(
sprintf(
'Invalid definition: metadata "%s" is not allowed. Did you mean "%s()" or "$%s"?',
$key,
$key,
$key,
)
);
}
}
}
private function validateTags(array $tags): void
{
foreach ($tags as $tag) {
if (!is_string($tag)) {
throw new InvalidConfigException('Invalid tag. Expected a string, got ' . var_export($tag, true) . '.');
}
}
}
private function setTags(string $id, array $tags): void
{
foreach ($tags as $tag) {
if (!isset($this->tags[$tag]) || !in_array($id, $this->tags[$tag], true)) {
$this->tags[$tag][] = $id;
}
}
}
private function setResetter(string $id, Closure $resetter): void
{
$this->resetters[$id] = $resetter;
}
/**
* Creates new instance by either interface name or alias.
*
* @param string $id The interface or an alias name that was previously registered.
*
* @throws CircularReferenceException
* @throws InvalidConfigException
* @throws NotFoundException
*
* @return mixed|object New built instance of the specified class.
*
* @internal
*/
private function build(string $id)
{
if ($this->isTagAlias($id)) {
return $this->getTaggedServices($id);
}
if (isset($this->building[$id])) {
if ($id === ContainerInterface::class) {
return $this;
}
throw new CircularReferenceException(sprintf(
'Circular reference to "%s" detected while building: %s.',
$id,
implode(', ', array_keys($this->building))
));
}
$this->building[$id] = 1;
try {
$object = $this->buildInternal($id);
} finally {
unset($this->building[$id]);
}
return $object;
}
private function isTagAlias(string $id): bool
{
return strncmp($id, 'tag@', 4) === 0;
}
private function getTaggedServices(string $tagAlias): array
{
$tag = substr($tagAlias, 4);
$services = [];
if (isset($this->tags[$tag])) {
foreach ($this->tags[$tag] as $service) {
$services[] = $this->get($service);
}
}
return $services;
}
/**
* @param string $id
*
* @throws InvalidConfigException
* @throws NotFoundException
*
* @return mixed|object
*/
private function buildInternal(string $id)
{
if ($this->definitions->has($id)) {
$definition = DefinitionNormalizer::normalize($this->definitions->get($id), $id);
return $definition->resolve($this->get(ContainerInterface::class));
}
throw new NotFoundException($id, $this->definitions->getBuildStack());
}
private function addProviders(array $providers): void
{
$extensions = [];
foreach ($providers as $provider) {
$providerInstance = $this->buildProvider($provider);
$extensions[] = $providerInstance->getExtensions();
$this->addProviderDefinitions($providerInstance);
}
foreach ($extensions as $providerExtensions) {
foreach ($providerExtensions as $id => $extension) {
if (!$this->definitions->has($id)) {
throw new InvalidConfigException("Extended service \"$id\" doesn't exist.");
}
$definition = $this->definitions->get($id);
if (!$definition instanceof ExtensibleService) {
$definition = new ExtensibleService($definition);
$this->definitions->set($id, $definition);
}
$definition->addExtension($extension);
}
}
}
/**
* Adds service provider definitions to the container.
*
* @param object $provider
*
* @throws InvalidConfigException
* @throws NotInstantiableException
*
* @see ServiceProviderInterface
*/
private function addProviderDefinitions($provider): void
{
$definitions = $provider->getDefinitions();
$this->setMultiple($definitions);
}
/**
* Builds service provider by definition.
*
* @param mixed $provider Class name or instance of provider.
*
* @throws InvalidConfigException If provider argument is not valid.
*
* @return ServiceProviderInterface Instance of service provider.
*
* @psalm-suppress MoreSpecificReturnType
*/
private function buildProvider($provider): ServiceProviderInterface
{
if ($this->validate && !(is_string($provider) || $provider instanceof ServiceProviderInterface)) {
throw new InvalidConfigException(
sprintf(
'Service provider should be a class name or an instance of %s. %s given.',
ServiceProviderInterface::class,
$this->getVariableType($provider)
)
);
}
$providerInstance = is_object($provider) ? $provider : new $provider();
if (!$providerInstance instanceof ServiceProviderInterface) {
throw new InvalidConfigException(
sprintf(
'Service provider should be an instance of %s. %s given.',
ServiceProviderInterface::class,
$this->getVariableType($providerInstance)
)
);
}
/**
* @psalm-suppress LessSpecificReturnStatement
*/
return $providerInstance;
}
/**
* @param mixed $variable
*/
private function getVariableType($variable): string
{
return is_object($variable) ? get_class($variable) : gettype($variable);
}
}