Test Failed
Pull Request — master (#316)
by Dmitriy
05:46 queued 02:55
created

Container   F

Complexity

Total Complexity 84

Size/Duplication

Total Lines 586
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 14
Bugs 2 Features 0
Metric Value
eloc 211
c 14
b 2
f 0
dl 0
loc 586
ccs 188
cts 188
cp 1
rs 2
wmc 84

19 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 14 1
A has() 0 11 3
C get() 0 53 14
B setTags() 0 36 7
B addProviders() 0 44 9
A setDelegates() 0 22 4
A setDefinitionResetter() 0 3 1
A buildProvider() 0 28 6
A validateDefinitionTags() 0 14 4
A addDefinition() 0 21 4
A build() 0 26 4
A validateMeta() 0 21 5
A validateDefinitionReset() 0 7 2
A buildInternal() 0 9 2
A addDefinitionToStorage() 0 6 2
A validateDefinition() 0 30 5
A getTaggedServices() 0 12 3
A setDefinitionTags() 0 5 4
A addDefinitions() 0 15 4

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