Passed
Pull Request — master (#354)
by Dmitriy
05:37 queued 03:06
created

Container::callHookAfterBuilt()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 2
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Di;
6
7
use Closure;
8
use Psr\Container\ContainerExceptionInterface;
9
use Psr\Container\ContainerInterface;
10
use Psr\Container\NotFoundExceptionInterface;
11
use Throwable;
12
use Yiisoft\Definitions\ArrayDefinition;
13
use Yiisoft\Definitions\DefinitionStorage;
14
use Yiisoft\Definitions\Exception\CircularReferenceException;
15
use Yiisoft\Definitions\Exception\InvalidConfigException;
16
use Yiisoft\Definitions\Exception\NotInstantiableException;
17
use Yiisoft\Definitions\Helpers\DefinitionValidator;
18
use Yiisoft\Di\Helpers\DefinitionNormalizer;
19
use Yiisoft\Di\Helpers\DefinitionParser;
20
use Yiisoft\Di\Helpers\TagHelper;
21
22
use function array_key_exists;
23
use function array_keys;
24
use function implode;
25
use function in_array;
26
use function is_array;
27
use function is_callable;
28
use function is_object;
29
use function is_string;
30
31
/**
32
 * Container implements a [dependency injection](https://en.wikipedia.org/wiki/Dependency_injection) container.
33
 */
34
final class Container implements ContainerInterface
35
{
36
    private const META_TAGS = 'tags';
37
    private const META_RESET = 'reset';
38
    private const META_AFTER_BUILT = 'afterBuilt';
39
    private const ALLOWED_META = [self::META_TAGS, self::META_RESET, self::META_AFTER_BUILT];
40
41
    /**
42
     * @var DefinitionStorage Storage of object definitions.
43
     */
44
    private DefinitionStorage $definitions;
45
46
    /**
47
     * @var array Used to collect IDs of objects instantiated during build
48
     * to detect circular references.
49
     */
50
    private array $building = [];
51
52
    /**
53
     * @var bool $validate If definitions should be validated.
54
     */
55
    private bool $validate;
56
57
    private array $instances = [];
58
59
    private CompositeContainer $delegates;
60
61
    /**
62
     * @var array Tagged service IDs. The structure is `['tagID' => ['service1', 'service2']]`.
63
     * @psalm-var array<string, list<string>>
64
     */
65
    private array $tags;
66
67
    /**
68
     * @var Closure[]
69
     */
70
    private array $resetters = [];
71
72
    /**
73
     * @var Closure[]
74
     */
75
    public array $afterBuiltHooks = [];
76
77
    private bool $useResettersFromMeta = true;
78
79
    /**
80
     * @param ContainerConfigInterface $config Container configuration.
81
     *
82
     * @throws InvalidConfigException If configuration is not valid.
83
     */
84 140
    public function __construct(ContainerConfigInterface $config)
85
    {
86 140
        $this->definitions = new DefinitionStorage(
87 140
            [
88 140
                ContainerInterface::class => $this,
89 140
                StateResetter::class => StateResetter::class,
90 140
            ],
91 140
            $config->useStrictMode()
92 140
        );
93 140
        $this->validate = $config->shouldValidate();
94 140
        $this->setTags($config->getTags());
95 137
        $this->addDefinitions($config->getDefinitions());
96 127
        $this->addProviders($config->getProviders());
97 121
        $this->setDelegates($config->getDelegates());
98
    }
99
100
    /**
101
     * Returns a value indicating whether the container has the definition of the specified name.
102
     *
103
     * @param string $id Class name, interface name or alias name.
104
     *
105
     * @return bool Whether the container is able to provide instance of class specified.
106
     *
107
     * @see addDefinition()
108
     */
109 47
    public function has(string $id): bool
110
    {
111 47
        if (TagHelper::isTagAlias($id)) {
112 3
            $tag = TagHelper::extractTagFromAlias($id);
113 3
            return isset($this->tags[$tag]);
114
        }
115
116
        try {
117 44
            return $this->definitions->has($id);
118 3
        } catch (CircularReferenceException) {
119 3
            return true;
120
        }
121
    }
122
123
    /**
124
     * Returns an instance by either interface name or alias.
125
     *
126
     * Same instance of the class will be returned each time this method is called.
127
     *
128
     * @param string $id The interface or an alias name that was previously registered.
129
     *
130
     * @throws CircularReferenceException
131
     * @throws InvalidConfigException
132
     * @throws NotFoundExceptionInterface
133
     * @throws NotInstantiableException
134
     * @throws BuildingException
135
     *
136
     * @return mixed|object An instance of the requested interface.
137
     *
138
     * @psalm-template T
139
     * @psalm-param string|class-string<T> $id
140
     * @psalm-return ($id is class-string ? T : mixed)
141
     */
142 121
    public function get(string $id)
143
    {
144 121
        $result = null;
145 121
        if (!array_key_exists($id, $this->instances)) {
146
            try {
147
                try {
148 121
                    $result = $this->instances[$id] = $this->build($id);
149 21
                } catch (NotFoundExceptionInterface $e) {
150 12
                    if (!$this->delegates->has($id)) {
151 9
                        throw $e;
152
                    }
153
154
                    /** @psalm-suppress MixedReturnStatement */
155 121
                    return $this->delegates->get($id);
156
                }
157 18
            } catch (Throwable $e) {
158 18
                if ($e instanceof ContainerExceptionInterface && !$e instanceof InvalidConfigException) {
159 16
                    throw $e;
160
                }
161 2
                throw new BuildingException($id, $e, $this->definitions->getBuildStack(), $e);
162
            }
163
        }
164 121
        $this->callHookAfterBuilt($id);
165
166 121
        if ($id === StateResetter::class) {
167 10
            $delegatesResetter = null;
168 10
            if ($this->delegates->has(StateResetter::class)) {
169 2
                $delegatesResetter = $this->delegates->get(StateResetter::class);
170
            }
171
172
            /** @var StateResetter $mainResetter */
173 10
            $mainResetter = $this->instances[$id];
174
175 10
            if ($this->useResettersFromMeta) {
176
                /** @var StateResetter[] $resetters */
177 7
                $resetters = [];
178 7
                foreach ($this->resetters as $serviceId => $callback) {
179 7
                    if (isset($this->instances[$serviceId])) {
180 7
                        $resetters[$serviceId] = $callback;
181
                    }
182
                }
183 7
                if ($delegatesResetter !== null) {
184 1
                    $resetters[] = $delegatesResetter;
185
                }
186 7
                $mainResetter->setResetters($resetters);
187 5
            } elseif ($delegatesResetter !== null) {
188 1
                $resetter = new StateResetter($this->get(ContainerInterface::class));
189 1
                $resetter->setResetters([$mainResetter, $delegatesResetter]);
190
191 1
                return $resetter;
192
            }
193
        }
194
195
        /** @psalm-suppress MixedReturnStatement */
196 121
        return $result ?? $this->instances[$id];
197
    }
198
199
    /**
200
     * Sets a definition to the container. Definition may be defined multiple ways.
201
     *
202
     * @param string $id ID to set definition for.
203
     * @param mixed $definition Definition to set.
204
     *
205
     * @throws InvalidConfigException
206
     *
207
     * @see DefinitionNormalizer::normalize()
208
     */
209 112
    private function addDefinition(string $id, mixed $definition): void
210
    {
211
        /** @var mixed $definition */
212 112
        [$definition, $meta] = DefinitionParser::parse($definition);
213 112
        if ($this->validate) {
214 112
            $this->validateDefinition($definition, $id);
215 109
            $this->validateMeta($meta);
216
        }
217
        /**
218
         * @psalm-var array{reset?:Closure,tags?:string[]} $meta
219
         */
220
221 103
        if (isset($meta[self::META_TAGS])) {
222 9
            $this->setDefinitionTags($id, $meta[self::META_TAGS]);
223
        }
224 103
        if (isset($meta[self::META_RESET])) {
225 7
            $this->setDefinitionResetter($id, $meta[self::META_RESET]);
226
        }
227 103
        if (isset($meta[self::META_AFTER_BUILT])) {
228 1
            $this->setAfterBuiltHook($id, $meta[self::META_AFTER_BUILT]);
229
        }
230
231 103
        unset($this->instances[$id]);
232 103
        $this->addDefinitionToStorage($id, $definition);
233
    }
234
235
    /**
236
     * Sets multiple definitions at once.
237
     *
238
     * @param array $config Definitions indexed by their IDs.
239
     *
240
     * @throws InvalidConfigException
241
     */
242 137
    private function addDefinitions(array $config): void
243
    {
244
        /** @var mixed $definition */
245 137
        foreach ($config as $id => $definition) {
246 111
            if ($this->validate && !is_string($id)) {
247 1
                throw new InvalidConfigException(
248 1
                    sprintf(
249 1
                        'Key must be a string. %s given.',
250 1
                        get_debug_type($id)
251 1
                    )
252 1
                );
253
            }
254
            /** @var string $id */
255
256 110
            $this->addDefinition($id, $definition);
257
        }
258
    }
259
260
    /**
261
     * Set container delegates.
262
     *
263
     * Each delegate must is a callable in format "function (ContainerInterface $container): ContainerInterface".
264
     * The container instance returned is used in case a service can not be found in primary container.
265
     *
266
     * @throws InvalidConfigException
267
     */
268 121
    private function setDelegates(array $delegates): void
269
    {
270 121
        $this->delegates = new CompositeContainer();
271 121
        $container = $this->get(ContainerInterface::class);
272
273 121
        foreach ($delegates as $delegate) {
274 6
            if (!$delegate instanceof Closure) {
275 1
                throw new InvalidConfigException(
276 1
                    'Delegate must be callable in format "function (ContainerInterface $container): ContainerInterface".'
277 1
                );
278
            }
279
280
            /** @var ContainerInterface */
281 5
            $delegate = $delegate($container);
282
283 5
            if (!$delegate instanceof ContainerInterface) {
284 1
                throw new InvalidConfigException(
285 1
                    'Delegate callable must return an object that implements ContainerInterface.'
286 1
                );
287
            }
288
289 4
            $this->delegates->attach($delegate);
290
        }
291 119
        $this->definitions->setDelegateContainer($this->delegates);
292
    }
293
294
    /**
295
     * @param mixed $definition Definition to validate.
296
     * @param string|null $id ID of the definition to validate.
297
     *
298
     * @throws InvalidConfigException
299
     */
300 112
    private function validateDefinition(mixed $definition, ?string $id = null): void
301
    {
302 112
        if (is_array($definition) && isset($definition[DefinitionParser::IS_PREPARED_ARRAY_DEFINITION_DATA])) {
303
            /** @var mixed $class */
304 48
            $class = $definition['class'];
305
306
            /** @var mixed $constructorArguments */
307 48
            $constructorArguments = $definition['__construct()'];
308
309
            /**
310
             * @var array $methodsAndProperties Is always array for prepared array definition data.
311
             *
312
             * @see DefinitionParser::parse()
313
             */
314 48
            $methodsAndProperties = $definition['methodsAndProperties'];
315
316 48
            $definition = array_merge(
317 48
                $class === null ? [] : [ArrayDefinition::CLASS_NAME => $class],
318 48
                [ArrayDefinition::CONSTRUCTOR => $constructorArguments],
319
                // extract only value from parsed definition method
320 48
                array_map(fn (array $data): mixed => $data[2], $methodsAndProperties),
321 48
            );
322
        }
323
324 112
        if ($definition instanceof ExtensibleService) {
325 1
            throw new InvalidConfigException(
326 1
                'Invalid definition. ExtensibleService is only allowed in provider extensions.'
327 1
            );
328
        }
329
330 111
        DefinitionValidator::validate($definition, $id);
331
    }
332
333
    /**
334
     * @throws InvalidConfigException
335
     */
336 109
    private function validateMeta(array $meta): void
337
    {
338
        /** @var mixed $value */
339 109
        foreach ($meta as $key => $value) {
340 23
            if (!in_array($key, self::ALLOWED_META, true)) {
341 3
                throw new InvalidConfigException(
342 3
                    sprintf(
343 3
                        'Invalid definition: metadata "%s" is not allowed. Did you mean "%s()" or "$%s"?',
344 3
                        $key,
345 3
                        $key,
346 3
                        $key,
347 3
                    )
348 3
                );
349
            }
350
351 21
            if ($key === self::META_TAGS) {
352 12
                $this->validateDefinitionTags($value);
353
            }
354
355 19
            if ($key === self::META_RESET) {
356 8
                $this->validateDefinitionReset($value);
357
            }
358
        }
359
    }
360
361
    /**
362
     * @throws InvalidConfigException
363
     */
364 12
    private function validateDefinitionTags(mixed $tags): void
365
    {
366 12
        if (!is_array($tags)) {
367 1
            throw new InvalidConfigException(
368 1
                sprintf(
369 1
                    'Invalid definition: tags should be array of strings, %s given.',
370 1
                    get_debug_type($tags)
371 1
                )
372 1
            );
373
        }
374
375 11
        foreach ($tags as $tag) {
376 11
            if (!is_string($tag)) {
377 1
                throw new InvalidConfigException('Invalid tag. Expected a string, got ' . var_export($tag, true) . '.');
378
            }
379
        }
380
    }
381
382
    /**
383
     * @throws InvalidConfigException
384
     */
385 8
    private function validateDefinitionReset(mixed $reset): void
386
    {
387 8
        if (!$reset instanceof Closure) {
388 1
            throw new InvalidConfigException(
389 1
                sprintf(
390 1
                    'Invalid definition: "reset" should be closure, %s given.',
391 1
                    get_debug_type($reset)
392 1
                )
393 1
            );
394
        }
395
    }
396
397
    /**
398
     * @throws InvalidConfigException
399
     */
400 140
    private function setTags(array $tags): void
401
    {
402 140
        if ($this->validate) {
403 140
            foreach ($tags as $tag => $services) {
404 5
                if (!is_string($tag)) {
405 1
                    throw new InvalidConfigException(
406 1
                        sprintf(
407 1
                            'Invalid tags configuration: tag should be string, %s given.',
408 1
                            $tag
409 1
                        )
410 1
                    );
411
                }
412 4
                if (!is_array($services)) {
413 1
                    throw new InvalidConfigException(
414 1
                        sprintf(
415 1
                            'Invalid tags configuration: tag should contain array of service IDs, %s given.',
416 1
                            get_debug_type($services)
417 1
                        )
418 1
                    );
419
                }
420
                /** @var mixed $service */
421 3
                foreach ($services as $service) {
422 3
                    if (!is_string($service)) {
423 1
                        throw new InvalidConfigException(
424 1
                            sprintf(
425 1
                                'Invalid tags configuration: service should be defined as class string, %s given.',
426 1
                                get_debug_type($service)
427 1
                            )
428 1
                        );
429
                    }
430
                }
431
            }
432
        }
433
        /** @psalm-var array<string, list<string>> $tags */
434
435 137
        $this->tags = $tags;
436
    }
437
438
    /**
439
     * @psalm-param string[] $tags
440
     */
441 9
    private function setDefinitionTags(string $id, array $tags): void
442
    {
443 9
        foreach ($tags as $tag) {
444 9
            if (!isset($this->tags[$tag]) || !in_array($id, $this->tags[$tag], true)) {
445 9
                $this->tags[$tag][] = $id;
446
            }
447
        }
448
    }
449
450 7
    private function setDefinitionResetter(string $id, Closure $resetter): void
451
    {
452 7
        $this->resetters[$id] = $resetter;
453
    }
454
455
    /**
456
     * Add definition to storage.
457
     *
458
     * @param string $id ID to set definition for.
459
     * @param mixed|object $definition Definition to set.
460
     *
461
     * @see $definitions
462
     */
463 103
    private function addDefinitionToStorage(string $id, $definition): void
464
    {
465 103
        $this->definitions->set($id, $definition);
466
467 103
        if ($id === StateResetter::class) {
468 5
            $this->useResettersFromMeta = false;
469
        }
470
    }
471
472
    /**
473
     * Creates new instance by either interface name or alias.
474
     *
475
     * @param string $id The interface or an alias name that was previously registered.
476
     *
477
     * @throws InvalidConfigException
478
     * @throws NotFoundExceptionInterface
479
     * @throws CircularReferenceException
480
     *
481
     * @return mixed|object New built instance of the specified class.
482
     *
483
     * @internal
484
     */
485 121
    private function build(string $id)
486
    {
487 121
        if (TagHelper::isTagAlias($id)) {
488 10
            return $this->getTaggedServices($id);
489
        }
490
491 121
        if (isset($this->building[$id])) {
492 121
            if ($id === ContainerInterface::class) {
493 121
                return $this;
494
            }
495 4
            throw new CircularReferenceException(
496 4
                sprintf(
497 4
                    'Circular reference to "%s" detected while building: %s.',
498 4
                    $id,
499 4
                    implode(', ', array_keys($this->building))
500 4
                )
501 4
            );
502
        }
503
504 121
        $this->building[$id] = 1;
505
        try {
506
            /** @var mixed $object */
507 121
            $object = $this->buildInternal($id);
508
        } finally {
509 121
            unset($this->building[$id]);
510
        }
511
512 121
        return $object;
513
    }
514
515 10
    private function getTaggedServices(string $tagAlias): array
516
    {
517 10
        $tag = TagHelper::extractTagFromAlias($tagAlias);
518 10
        $services = [];
519 10
        if (isset($this->tags[$tag])) {
520 9
            foreach ($this->tags[$tag] as $service) {
521
                /** @var mixed */
522 9
                $services[] = $this->get($service);
523
            }
524
        }
525
526 10
        return $services;
527
    }
528
529
    /**
530
     * @throws NotFoundExceptionInterface
531
     * @throws InvalidConfigException
532
     *
533
     * @return mixed|object
534
     */
535 121
    private function buildInternal(string $id)
536
    {
537 121
        if ($this->definitions->has($id)) {
538 121
            $definition = DefinitionNormalizer::normalize($this->definitions->get($id), $id);
539
540 121
            return $definition->resolve($this->get(ContainerInterface::class));
541
        }
542
543 12
        throw new NotFoundException($id, $this->definitions->getBuildStack());
544
    }
545
546
    /**
547
     * @throws CircularReferenceException
548
     * @throws InvalidConfigException
549
     */
550 127
    private function addProviders(array $providers): void
551
    {
552 127
        $extensions = [];
553
        /** @var mixed $provider */
554 127
        foreach ($providers as $provider) {
555 16
            $providerInstance = $this->buildProvider($provider);
556 14
            $extensions[] = $providerInstance->getExtensions();
557 14
            $this->addDefinitions($providerInstance->getDefinitions());
558
        }
559
560 125
        foreach ($extensions as $providerExtensions) {
561
            /** @var mixed $extension */
562 14
            foreach ($providerExtensions as $id => $extension) {
563 10
                if (!is_string($id)) {
564 1
                    throw new InvalidConfigException(
565 1
                        sprintf('Extension key must be a service ID as string, %s given.', $id)
566 1
                    );
567
                }
568
569 9
                if ($id === ContainerInterface::class) {
570 1
                    throw new InvalidConfigException('ContainerInterface extensions are not allowed.');
571
                }
572
573 8
                if (!$this->definitions->has($id)) {
574 1
                    throw new InvalidConfigException("Extended service \"$id\" doesn't exist.");
575
                }
576
577 8
                if (!is_callable($extension)) {
578 1
                    throw new InvalidConfigException(
579 1
                        sprintf(
580 1
                            'Extension of service should be callable, %s given.',
581 1
                            get_debug_type($extension)
582 1
                        )
583 1
                    );
584
                }
585
586
                /** @var mixed $definition */
587 7
                $definition = $this->definitions->get($id);
588 7
                if (!$definition instanceof ExtensibleService) {
589 7
                    $definition = new ExtensibleService($definition, $id);
590 7
                    $this->addDefinitionToStorage($id, $definition);
591
                }
592
593 7
                $definition->addExtension($extension);
594
            }
595
        }
596
    }
597
598
    /**
599
     * Builds service provider by definition.
600
     *
601
     * @param mixed $provider Class name or instance of provider.
602
     *
603
     * @throws InvalidConfigException If provider argument is not valid.
604
     *
605
     * @return ServiceProviderInterface Instance of service provider.
606
     */
607 16
    private function buildProvider(mixed $provider): ServiceProviderInterface
608
    {
609 16
        if ($this->validate && !(is_string($provider) || $provider instanceof ServiceProviderInterface)) {
610 1
            throw new InvalidConfigException(
611 1
                sprintf(
612 1
                    'Service provider should be a class name or an instance of %s. %s given.',
613 1
                    ServiceProviderInterface::class,
614 1
                    get_debug_type($provider)
615 1
                )
616 1
            );
617
        }
618
619
        /**
620
         * @psalm-suppress MixedMethodCall Service provider defined as class string
621
         * should container public constructor, otherwise throws error.
622
         */
623 15
        $providerInstance = is_object($provider) ? $provider : new $provider();
624 15
        if (!$providerInstance instanceof ServiceProviderInterface) {
625 1
            throw new InvalidConfigException(
626 1
                sprintf(
627 1
                    'Service provider should be an instance of %s. %s given.',
628 1
                    ServiceProviderInterface::class,
629 1
                    get_debug_type($providerInstance)
630 1
                )
631 1
            );
632
        }
633
634 14
        return $providerInstance;
635
    }
636
637 121
    private function callHookAfterBuilt(string $id): void
638
    {
639 121
        if (isset($this->afterBuiltHooks[$id])) {
640 1
            $this->afterBuiltHooks[$id]->call($this, $this, $id);
641
        }
642
    }
643
644 1
    private function setAfterBuiltHook(string $id, Closure $callback): void
645
    {
646 1
        $this->afterBuiltHooks[$id] = $callback;
647
    }
648
}
649