Passed
Push — psalm ( 5f77d0 )
by Sergei
03:54
created

Container::setDefinitionResetter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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