Passed
Push — add-rector ( 156153...893674 )
by Sergei
13:15 queued 10:41
created

Container::getVariableType()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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