Passed
Push — master ( 0b1876...128832 )
by Alexander
02:14
created

Container::addDefinitionToStorage()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

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