Passed
Pull Request — master (#288)
by Alexander
03:25
created

Container   F

Complexity

Total Complexity 87

Size/Duplication

Total Lines 622
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 14
Bugs 2 Features 0
Metric Value
eloc 212
c 14
b 2
f 0
dl 0
loc 622
ccs 227
cts 227
cp 1
rs 2
wmc 87

22 Methods

Rating   Name   Duplication   Size   Complexity  
A has() 0 16 4
A __construct() 0 14 1
C get() 0 47 12
A addProviderDefinitions() 0 4 1
B setTags() 0 35 7
A set() 0 21 4
B addProviders() 0 44 9
A setDelegates() 0 22 4
A setDefinitionResetter() 0 3 1
A buildProvider() 0 33 6
A validateDefinitionTags() 0 14 4
A build() 0 26 4
A validateMeta() 0 21 5
A validateDefinitionReset() 0 7 2
A addDefinitionToStorage() 0 6 2
A isTagAlias() 0 3 1
A buildInternal() 0 9 2
A setMultiple() 0 15 4
A validateDefinition() 0 30 5
A getTaggedServices() 0 13 3
A setDefinitionTags() 0 5 4
A getVariableType() 0 3 2

How to fix   Complexity   

Complex Class

Complex classes like Container often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Container, and based on these observations, apply Extract Interface, too.

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