Passed
Push — master ( 0d4d0d...eaa6f1 )
by Sergei
02:37
created

Container::get()   B

Complexity

Conditions 11
Paths 20

Size

Total Lines 46
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 11

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 11
eloc 25
c 1
b 0
f 0
nc 20
nop 1
dl 0
loc 46
ccs 25
cts 25
cp 1
crap 11
rs 7.3166

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