Passed
Pull Request — master (#288)
by Alexander
02:32
created

Container::get()   C

Complexity

Conditions 12
Paths 21

Size

Total Lines 51
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 27
CRAP Score 12

Importance

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

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