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