Container::build()   A
last analyzed

Complexity

Conditions 5
Paths 8

Size

Total Lines 34
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 5

Importance

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