Passed
Push — lazy-services ( fedff5...51fefa )
by Dmitriy
03:56
created

Container::checkClassOnNullForLazyService()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 3.4578

Importance

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