Test Failed
Push — fix-exception-messages ( 28ab20 )
by Dmitriy
12:27
created

Container   F

Complexity

Total Complexity 83

Size/Duplication

Total Lines 585
Duplicated Lines 0 %

Importance

Changes 13
Bugs 2 Features 0
Metric Value
eloc 211
c 13
b 2
f 0
dl 0
loc 585
rs 2
wmc 83

19 Methods

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