Passed
Pull Request — master (#288)
by Dmitriy
03:02
created

Container::get()   C

Complexity

Conditions 12
Paths 21

Size

Total Lines 49
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 12
eloc 26
c 1
b 0
f 0
nc 21
nop 1
dl 0
loc 49
ccs 25
cts 25
cp 1
crap 12
rs 6.9666

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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