Passed
Pull Request — master (#232)
by Dmitriy
05:35 queued 02:57
created

Container::decorateLazy()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 8.9038

Importance

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