Passed
Pull Request — master (#364)
by Alexander
23:10 queued 19:59
created

Container::buildInternal()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

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