Passed
Pull Request — master (#232)
by Dmitriy
10:06 queued 07:40
created

Container::buildInternal()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

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