Passed
Pull Request — master (#354)
by Dmitriy
05:05 queued 02:28
created

Container::setAfterBuiltHook()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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