Test Failed
Pull Request — master (#316)
by Dmitriy
05:41 queued 03:12
created

Container::get()   C

Complexity

Conditions 14
Paths 27

Size

Total Lines 53
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 14

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 14
eloc 30
c 2
b 0
f 0
nc 27
nop 1
dl 0
loc 53
ccs 23
cts 23
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 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 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 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, $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
                // extract only value from parsed definition method
308
                array_map(fn (array $data): mixed => $data[2], $methodsAndProperties),
309
            );
310
        }
311
312 104
        if ($definition instanceof ExtensibleService) {
313
            throw new InvalidConfigException(
314
                'Invalid definition. ExtensibleService is only allowed in provider extensions.'
315 104
            );
316 22
        }
317 3
318 3
        DefinitionValidator::validate($definition, $id);
319
    }
320
321
    /**
322
     * @throws InvalidConfigException
323
     */
324
    private function validateMeta(array $meta): void
325
    {
326
        /** @var mixed $value */
327 20
        foreach ($meta as $key => $value) {
328 12
            if (!in_array($key, self::ALLOWED_META, true)) {
329
                throw new InvalidConfigException(
330
                    sprintf(
331 18
                        'Invalid definition: metadata "%s" is not allowed. Did you mean "%s()" or "$%s"?',
332 8
                        $key,
333
                        $key,
334
                        $key,
335
                    )
336
                );
337
            }
338
339
            if ($key === self::META_TAGS) {
340 12
                $this->validateDefinitionTags($value);
341
            }
342 12
343 1
            if ($key === self::META_RESET) {
344 1
                $this->validateDefinitionReset($value);
345
            }
346 1
        }
347
    }
348
349
    /**
350
     * @throws InvalidConfigException
351 11
     */
352 11
    private function validateDefinitionTags(mixed $tags): void
353 1
    {
354
        if (!is_array($tags)) {
355
            throw new InvalidConfigException(
356
                sprintf(
357
                    'Invalid definition: tags should be array of strings, %s given.',
358
                    get_debug_type($tags)
359
                )
360
            );
361 8
        }
362
363 8
        foreach ($tags as $tag) {
364 1
            if (!is_string($tag)) {
365 1
                throw new InvalidConfigException('Invalid tag. Expected a string, got ' . var_export($tag, true) . '.');
366
            }
367 1
        }
368
    }
369
370
    /**
371
     * @throws InvalidConfigException
372
     */
373
    private function validateDefinitionReset(mixed $reset): void
374
    {
375
        if (!$reset instanceof Closure) {
376 134
            throw new InvalidConfigException(
377
                sprintf(
378 134
                    'Invalid definition: "reset" should be closure, %s given.',
379 134
                    get_debug_type($reset)
380 5
                )
381 1
            );
382 1
        }
383
    }
384
385
    /**
386
     * @throws InvalidConfigException
387
     */
388 4
    private function setTags(array $tags): void
389 1
    {
390 1
        if ($this->validate) {
391
            foreach ($tags as $tag => $services) {
392 1
                if (!is_string($tag)) {
393
                    throw new InvalidConfigException(
394
                        sprintf(
395
                            'Invalid tags configuration: tag should be string, %s given.',
396
                            $tag
397 3
                        )
398 3
                    );
399 1
                }
400 1
                if (!is_array($services)) {
401
                    throw new InvalidConfigException(
402 1
                        sprintf(
403
                            'Invalid tags configuration: tag should contain array of service IDs, %s given.',
404
                            get_debug_type($services)
405
                        )
406
                    );
407
                }
408
                /** @var mixed $service */
409
                foreach ($services as $service) {
410
                    if (!is_string($service)) {
411 131
                        throw new InvalidConfigException(
412
                            sprintf(
413
                                'Invalid tags configuration: service should be defined as class string, %s given.',
414
                                get_debug_type($service)
415
                            )
416
                        );
417 9
                    }
418
                }
419 9
            }
420 9
        }
421 9
        /** @psalm-var array<string, list<string>> $tags */
422
423
        $this->tags = $tags;
424
    }
425
426 7
    /**
427
     * @psalm-param string[] $tags
428 7
     */
429
    private function setDefinitionTags(string $id, array $tags): void
430
    {
431
        foreach ($tags as $tag) {
432
            if (!isset($this->tags[$tag]) || !in_array($id, $this->tags[$tag], true)) {
433
                $this->tags[$tag][] = $id;
434
            }
435
        }
436
    }
437
438
    private function setDefinitionResetter(string $id, Closure $resetter): void
439 98
    {
440
        $this->resetters[$id] = $resetter;
441 98
    }
442
443 98
    /**
444 5
     * Add definition to storage.
445
     *
446
     * @param string $id ID to set definition for.
447
     * @param mixed|object $definition Definition to set.
448
     *
449
     * @see $definitions
450
     */
451
    private function addDefinitionToStorage(string $id, $definition): void
452
    {
453
        $this->definitions->set($id, $definition);
454
455
        if ($id === StateResetter::class) {
456
            $this->useResettersFromMeta = false;
457
        }
458
    }
459
460
    /**
461 99
     * Creates new instance by either interface name or alias.
462
     *
463 99
     * @param string $id The interface or an alias name that was previously registered.
464 10
     *
465
     * @throws InvalidConfigException
466
     * @throws NotFoundExceptionInterface
467 98
     * @throws CircularReferenceException
468 89
     *
469 89
     * @return mixed|object New built instance of the specified class.
470
     *
471 4
     * @internal
472
     */
473
    private function build(string $id)
474 4
    {
475
        if (TagHelper::isTagAlias($id)) {
476
            return $this->getTaggedServices($id);
477
        }
478 98
479
        if (isset($this->building[$id])) {
480
            if ($id === ContainerInterface::class) {
481 98
                return $this;
482 89
            }
483 98
            throw new CircularReferenceException(
484
                sprintf(
485
                    'Circular reference to "%s" detected while building: %s.',
486 89
                    $id,
487
                    implode(', ', array_keys($this->building))
488
                )
489 10
            );
490
        }
491 10
492 10
        $this->building[$id] = 1;
493 10
        try {
494 9
            /** @var mixed $object */
495
            $object = $this->buildInternal($id);
496 9
        } finally {
497
            unset($this->building[$id]);
498
        }
499
500 10
        return $object;
501
    }
502
503
    private function getTaggedServices(string $tagAlias): array
504
    {
505
        $tag = TagHelper::extractTagFromAlias($tagAlias);
506
        $services = [];
507
        if (isset($this->tags[$tag])) {
508
            foreach ($this->tags[$tag] as $service) {
509 98
                /** @var mixed */
510
                $services[] = $this->get($service);
511 98
            }
512 89
        }
513
514 89
        return $services;
515
    }
516
517 11
    /**
518
     * @throws NotFoundExceptionInterface
519
     * @throws InvalidConfigException
520
     *
521
     * @return mixed|object
522
     */
523
    private function buildInternal(string $id)
524 122
    {
525
        if ($this->definitions->has($id)) {
526 122
            $definition = DefinitionNormalizer::normalize($this->definitions->get($id), $id);
527
528 122
            return $definition->resolve($this->get(ContainerInterface::class));
529 15
        }
530 13
531 13
        throw new NotFoundException($id, $this->definitions->getBuildStack());
532
    }
533
534 120
    /**
535
     * @throws CircularReferenceException
536 13
     * @throws InvalidConfigException
537 10
     */
538 1
    private function addProviders(array $providers): void
539 1
    {
540
        $extensions = [];
541
        /** @var mixed $provider */
542
        foreach ($providers as $provider) {
543 9
            $providerInstance = $this->buildProvider($provider);
544 1
            $extensions[] = $providerInstance->getExtensions();
545
            $this->addDefinitions($providerInstance->getDefinitions());
546
        }
547 8
548 1
        foreach ($extensions as $providerExtensions) {
549
            /** @var mixed $extension */
550
            foreach ($providerExtensions as $id => $extension) {
551 8
                if (!is_string($id)) {
552 1
                    throw new InvalidConfigException(
553 1
                        sprintf('Extension key must be a service ID as string, %s given.', $id)
554
                    );
555 1
                }
556
557
                if ($id === ContainerInterface::class) {
558
                    throw new InvalidConfigException('ContainerInterface extensions are not allowed.');
559
                }
560
561 7
                if (!$this->definitions->has($id)) {
562 7
                    throw new InvalidConfigException("Extended service \"$id\" doesn't exist.");
563 7
                }
564 7
565
                if (!is_callable($extension)) {
566
                    throw new InvalidConfigException(
567 7
                        sprintf(
568
                            'Extension of service should be callable, %s given.',
569
                            get_debug_type($extension)
570
                        )
571
                    );
572
                }
573
574
                /** @var mixed $definition */
575
                $definition = $this->definitions->get($id);
576
                if (!$definition instanceof ExtensibleService) {
577
                    $definition = new ExtensibleService($definition, $id);
578
                    $this->addDefinitionToStorage($id, $definition);
579
                }
580
581 15
                $definition->addExtension($extension);
582
            }
583 15
        }
584 1
    }
585 1
586
    /**
587
     * Builds service provider by definition.
588 1
     *
589
     * @param mixed $provider Class name or instance of provider.
590
     *
591
     * @throws InvalidConfigException If provider argument is not valid.
592
     *
593
     * @return ServiceProviderInterface Instance of service provider.
594
     */
595
    private function buildProvider(mixed $provider): ServiceProviderInterface
596
    {
597 14
        if ($this->validate && !(is_string($provider) || $provider instanceof ServiceProviderInterface)) {
598 14
            throw new InvalidConfigException(
599 1
                sprintf(
600 1
                    'Service provider should be a class name or an instance of %s. %s given.',
601
                    ServiceProviderInterface::class,
602
                    get_debug_type($provider)
603 1
                )
604
            );
605
        }
606
607
        /**
608 13
         * @psalm-suppress MixedMethodCall Service provider defined as class string
609
         * should container public constructor, otherwise throws error.
610
         */
611
        $providerInstance = is_object($provider) ? $provider : new $provider();
612
        if (!$providerInstance instanceof ServiceProviderInterface) {
613
            throw new InvalidConfigException(
614
                sprintf(
615
                    'Service provider should be an instance of %s. %s given.',
616
                    ServiceProviderInterface::class,
617
                    get_debug_type($providerInstance)
618
                )
619
            );
620
        }
621
622
        return $providerInstance;
623
    }
624
}
625