Passed
Push — master ( d91794...2a9432 )
by Alexander
02:31
created

Container::validateDefinitionReset()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

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