Passed
Pull Request — master (#232)
by Dmitriy
12:41
created

Container::decorateLazy()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 8.9038

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 11
c 1
b 0
f 0
nc 3
nop 2
dl 0
loc 17
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\DefinitionStorage;
14
use Yiisoft\Definitions\Contract\DefinitionInterface;
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 144
    public function __construct(ContainerConfigInterface $config)
81
    {
82 144
        $this->definitions = new DefinitionStorage(
83 144
            [
84 144
                ContainerInterface::class => $this,
85 144
                StateResetter::class => StateResetter::class,
86 144
            ],
87 144
            $config->useStrictMode()
88 144
        );
89 144
        $this->validate = $config->shouldValidate();
90 144
        $this->setTags($config->getTags());
91 141
        $this->addDefinitions($config->getDefinitions());
92 131
        $this->addProviders($config->getProviders());
93 125
        $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 125
    public function get(string $id)
139
    {
140 125
        if (!array_key_exists($id, $this->instances)) {
141
            try {
142
                try {
143 125
                    $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 125
                    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 125
        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 125
        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 116
    private function addDefinition(string $id, mixed $definition): void
204
    {
205
        /** @var mixed $definition */
206 116
        [$definition, $meta] = DefinitionParser::parse($definition);
207 116
        if ($this->validate) {
208 116
            $this->validateDefinition($definition, $id);
209 113
            $this->validateMeta($meta);
210
        }
211
        /**
212
         * @psalm-var array{reset?:Closure,tags?:string[]} $meta
213
         */
214
215 107
        if (isset($meta[self::META_TAGS])) {
216 9
            $this->setDefinitionTags($id, $meta[self::META_TAGS]);
217
        }
218 107
        if (isset($meta[self::META_RESET])) {
219 7
            $this->setDefinitionResetter($id, $meta[self::META_RESET]);
220
        }
221 107
        if (isset($meta[self::META_LAZY]) && $meta[self::META_LAZY] === true) {
222 5
            $definition = $this->decorateLazy($id, $definition);
223
        }
224
225 107
        unset($this->instances[$id]);
226 107
        $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 141
    private function addDefinitions(array $config): void
237
    {
238
        /** @var mixed $definition */
239 141
        foreach ($config as $id => $definition) {
240 115
            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 114
            $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
     * @param array $delegates
261
     *
262
     * @throws InvalidConfigException
263
     */
264 125
    private function setDelegates(array $delegates): void
265
    {
266 125
        $this->delegates = new CompositeContainer();
267 125
        $container = $this->get(ContainerInterface::class);
268
269 125
        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 123
        $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 116
    private function validateDefinition(mixed $definition, ?string $id = null): void
297
    {
298 116
        if (is_array($definition) && isset($definition[DefinitionParser::IS_PREPARED_ARRAY_DEFINITION_DATA])) {
299
            /** @var mixed $class */
300 50
            $class = $definition['class'];
301
302
            /** @var mixed $constructorArguments */
303 50
            $constructorArguments = $definition['__construct()'];
304
305
            /**
306
             * @var array $methodsAndProperties Is always array for prepared array definition data.
307
             *
308
             * @see DefinitionParser::parse()
309
             */
310 50
            $methodsAndProperties = $definition['methodsAndProperties'];
311
312 50
            $definition = array_merge(
313 50
                $class === null ? [] : [ArrayDefinition::CLASS_NAME => $class],
314 50
                [ArrayDefinition::CONSTRUCTOR => $constructorArguments],
315
                // extract only value from parsed definition method
316 50
                array_map(fn (array $data): mixed => $data[2], $methodsAndProperties),
317 50
            );
318
        }
319
320 116
        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 115
        DefinitionValidator::validate($definition, $id);
327
    }
328
329
    /**
330
     * @throws InvalidConfigException
331
     */
332 113
    private function validateMeta(array $meta): void
333
    {
334
        /** @var mixed $value */
335 113
        foreach ($meta as $key => $value) {
336 27
            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 25
            if ($key === self::META_TAGS) {
348 12
                $this->validateDefinitionTags($value);
349
            }
350
351 23
            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 144
    private function setTags(array $tags): void
397
    {
398 144
        if ($this->validate) {
399 144
            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 141
        $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 107
    private function addDefinitionToStorage(string $id, $definition): void
460
    {
461 107
        $this->definitions->set($id, $definition);
462
463 107
        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 125
    private function build(string $id)
482
    {
483 125
        if (TagHelper::isTagAlias($id)) {
484 10
            return $this->getTaggedServices($id);
485
        }
486
487 125
        if (isset($this->building[$id])) {
488 125
            if ($id === ContainerInterface::class) {
489 125
                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 125
        $this->building[$id] = 1;
501
        try {
502
            /** @var mixed $object */
503 125
            $object = $this->buildInternal($id);
504
        } finally {
505 125
            unset($this->building[$id]);
506
        }
507
508 125
        return $object;
509
    }
510
511 10
    private function getTaggedServices(string $tagAlias): array
512
    {
513 10
        $tag = TagHelper::extractTagFromAlias($tagAlias);
514 10
        $services = [];
515 10
        if (isset($this->tags[$tag])) {
516 9
            foreach ($this->tags[$tag] as $service) {
517
                /** @var mixed */
518 9
                $services[] = $this->get($service);
519
            }
520
        }
521
522 10
        return $services;
523
    }
524
525
    /**
526
     * @throws NotFoundExceptionInterface
527
     * @throws InvalidConfigException
528
     *
529
     * @return mixed|object
530
     */
531 125
    private function buildInternal(string $id)
532
    {
533 125
        if ($this->definitions->has($id)) {
534 125
            $definition = DefinitionNormalizer::normalize($this->definitions->get($id), $id);
535
536 125
            return $definition->resolve($this->get(ContainerInterface::class));
537
        }
538
539 12
        throw new NotFoundException($id, $this->definitions->getBuildStack());
540
    }
541
542
    /**
543
     * @throws CircularReferenceException
544
     * @throws InvalidConfigException
545
     */
546 131
    private function addProviders(array $providers): void
547
    {
548 131
        $extensions = [];
549
        /** @var mixed $provider */
550 131
        foreach ($providers as $provider) {
551 16
            $providerInstance = $this->buildProvider($provider);
552 14
            $extensions[] = $providerInstance->getExtensions();
553 14
            $this->addDefinitions($providerInstance->getDefinitions());
554
        }
555
556 129
        foreach ($extensions as $providerExtensions) {
557
            /** @var mixed $extension */
558 14
            foreach ($providerExtensions as $id => $extension) {
559 10
                if (!is_string($id)) {
560 1
                    throw new InvalidConfigException(
561 1
                        sprintf('Extension key must be a service ID as string, %s given.', $id)
562 1
                    );
563
                }
564
565 9
                if ($id === ContainerInterface::class) {
566 1
                    throw new InvalidConfigException('ContainerInterface extensions are not allowed.');
567
                }
568
569 8
                if (!$this->definitions->has($id)) {
570 1
                    throw new InvalidConfigException("Extended service \"$id\" doesn't exist.");
571
                }
572
573 8
                if (!is_callable($extension)) {
574 1
                    throw new InvalidConfigException(
575 1
                        sprintf(
576 1
                            'Extension of service should be callable, %s given.',
577 1
                            get_debug_type($extension)
578 1
                        )
579 1
                    );
580
                }
581
582
                /** @var mixed $definition */
583 7
                $definition = $this->definitions->get($id);
584 7
                if (!$definition instanceof ExtensibleService) {
585 7
                    $definition = new ExtensibleService($definition, $id);
586 7
                    $this->addDefinitionToStorage($id, $definition);
587
                }
588
589 7
                $definition->addExtension($extension);
590
            }
591
        }
592
    }
593
594
    /**
595
     * Builds service provider by definition.
596
     *
597
     * @param mixed $provider Class name or instance of provider.
598
     *
599
     * @throws InvalidConfigException If provider argument is not valid.
600
     *
601
     * @return ServiceProviderInterface Instance of service provider.
602
     */
603 16
    private function buildProvider(mixed $provider): ServiceProviderInterface
604
    {
605 16
        if ($this->validate && !(is_string($provider) || $provider instanceof ServiceProviderInterface)) {
606 1
            throw new InvalidConfigException(
607 1
                sprintf(
608 1
                    'Service provider should be a class name or an instance of %s. %s given.',
609 1
                    ServiceProviderInterface::class,
610 1
                    get_debug_type($provider)
611 1
                )
612 1
            );
613
        }
614
615
        /**
616
         * @psalm-suppress MixedMethodCall Service provider defined as class string
617
         * should container public constructor, otherwise throws error.
618
         */
619 15
        $providerInstance = is_object($provider) ? $provider : new $provider();
620 15
        if (!$providerInstance instanceof ServiceProviderInterface) {
621 1
            throw new InvalidConfigException(
622 1
                sprintf(
623 1
                    'Service provider should be an instance of %s. %s given.',
624 1
                    ServiceProviderInterface::class,
625 1
                    get_debug_type($providerInstance)
626 1
                )
627 1
            );
628
        }
629
630 14
        return $providerInstance;
631
    }
632
633 5
    private function decorateLazy(string $id, mixed $definition): DefinitionInterface
634
    {
635 5
        if (class_exists($id) || interface_exists($id)) {
636 4
            $class = $id;
637 1
        } elseif (is_array($definition) && array_key_exists(ArrayDefinition::CLASS_NAME, $definition)) {
638 1
            $class = (string) $definition[ArrayDefinition::CLASS_NAME];
639
        } else {
640
            throw new InvalidConfigException(
641
                sprintf(
642
                    'Invalid definition: lazy services are only available with array definitions or references. Got type "%s" for definition ID: "%s"',
643
                    get_debug_type($definition),
644
                    $id,
645
                )
646
            );
647
        }
648
649 5
        return new LazyDefinition($definition, $class);
650
    }
651
}
652