Passed
Push — master ( f184eb...e0b5ba )
by Dmitriy
09:27 queued 06:41
created

Container::get()   C

Complexity

Conditions 14
Paths 27

Size

Total Lines 53
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 29
CRAP Score 14

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 14
eloc 30
c 1
b 0
f 0
nc 27
nop 1
dl 0
loc 53
ccs 29
cts 29
cp 1
crap 14
rs 6.2666

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