Passed
Pull Request — master (#290)
by Dmitriy
03:01
created

Container::addProviders()   B

Complexity

Conditions 9
Paths 16

Size

Total Lines 44
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 9

Importance

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