Passed
Pull Request — master (#232)
by Dmitriy
06:50 queued 04:20
created

Container::decorateLazy()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4.432

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 12
nc 3
nop 2
dl 0
loc 18
ccs 7
cts 10
cp 0.7
crap 4.432
rs 9.8666
c 1
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 139
    public function __construct(ContainerConfigInterface $config)
81
    {
82 139
        $this->definitions = new DefinitionStorage(
83
            [
84
                ContainerInterface::class => $this,
85
                StateResetter::class => StateResetter::class,
86
            ],
87 139
            $config->useStrictMode()
88
        );
89 139
        $this->validate = $config->shouldValidate();
90 139
        $this->setTags($config->getTags());
91 136
        $this->addDefinitions($config->getDefinitions());
92 127
        $this->addProviders($config->getProviders());
93 121
        $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 104
    public function get(string $id)
138
    {
139 104
        if (!array_key_exists($id, $this->instances)) {
140
            try {
141 104
                $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 95
        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 95
        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 111
    private function addDefinition(string $id, mixed $definition): void
196
    {
197
        /** @var mixed $definition */
198 111
        [$definition, $meta] = DefinitionParser::parse($definition);
199 111
        if ($this->validate) {
200 111
            $this->validateDefinition($definition, $id);
201 109
            $this->validateMeta($meta);
202
        }
203
        /**
204
         * @psalm-var array{reset?:Closure,tags?:string[]} $meta
205
         */
206
207 103
        if (isset($meta[self::META_TAGS])) {
208 9
            $this->setDefinitionTags($id, $meta[self::META_TAGS]);
209
        }
210 103
        if (isset($meta[self::META_RESET])) {
211 7
            $this->setDefinitionResetter($id, $meta[self::META_RESET]);
212
        }
213 103
        if (isset($meta[self::META_LAZY]) && $meta[self::META_LAZY] === true) {
214 5
            $definition = $this->decorateLazy($id, $definition);
215
        }
216
217 103
        unset($this->instances[$id]);
218 103
        $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 136
    private function addDefinitions(array $config): void
229
    {
230
        /** @var mixed $definition */
231 136
        foreach ($config as $id => $definition) {
232 112
            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 111
            $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 121
    private function setDelegates(array $delegates): void
257
    {
258 121
        $this->delegates = new CompositeContainer();
259 121
        foreach ($delegates as $delegate) {
260 5
            if (!$delegate instanceof Closure) {
261 1
                throw new InvalidConfigException(
262
                    'Delegate must be callable in format "function (ContainerInterface $container): ContainerInterface".'
263
                );
264
            }
265
266
            /** @var ContainerInterface */
267 4
            $delegate = $delegate($this);
268
269 4
            if (!$delegate instanceof ContainerInterface) {
270 1
                throw new InvalidConfigException(
271
                    'Delegate callable must return an object that implements ContainerInterface.'
272
                );
273
            }
274
275 3
            $this->delegates->attach($delegate);
276
        }
277 119
        $this->definitions->setDelegateContainer($this->delegates);
278
    }
279
280
    /**
281
     * @param mixed $definition Definition to validate.
282
     * @param string|null $id ID of the definition to validate.
283
     *
284
     * @throws InvalidConfigException
285
     */
286 111
    private function validateDefinition(mixed $definition, ?string $id = null): void
287
    {
288 111
        if (is_array($definition) && isset($definition[DefinitionParser::IS_PREPARED_ARRAY_DEFINITION_DATA])) {
289
            /** @var mixed $class */
290 49
            $class = $definition['class'];
291
292
            /** @var mixed $constructorArguments */
293 49
            $constructorArguments = $definition['__construct()'];
294
295
            /**
296
             * @var array $methodsAndProperties Is always array for prepared array definition data.
297
             *
298
             * @see DefinitionParser::parse()
299
             */
300 49
            $methodsAndProperties = $definition['methodsAndProperties'];
301
302 49
            $definition = array_merge(
303 49
                $class === null ? [] : [ArrayDefinition::CLASS_NAME => $class],
304
                [ArrayDefinition::CONSTRUCTOR => $constructorArguments],
305
                $methodsAndProperties,
306
            );
307
        }
308
309 111
        if ($definition instanceof ExtensibleService) {
310 1
            throw new InvalidConfigException(
311
                'Invalid definition. ExtensibleService is only allowed in provider extensions.'
312
            );
313
        }
314
315 110
        DefinitionValidator::validate($definition, $id);
316
    }
317
318
    /**
319
     * @throws InvalidConfigException
320
     */
321 109
    private function validateMeta(array $meta): void
322
    {
323
        /** @var mixed $value */
324 109
        foreach ($meta as $key => $value) {
325 27
            if (!in_array($key, self::ALLOWED_META, true)) {
326 3
                throw new InvalidConfigException(
327 3
                    sprintf(
328
                        'Invalid definition: metadata "%s" is not allowed. Did you mean "%s()" or "$%s"?',
329
                        $key,
330
                        $key,
331
                        $key,
332
                    )
333
                );
334
            }
335
336 25
            if ($key === self::META_TAGS) {
337 12
                $this->validateDefinitionTags($value);
338
            }
339
340 23
            if ($key === self::META_RESET) {
341 8
                $this->validateDefinitionReset($value);
342
            }
343
        }
344
    }
345
346
    /**
347
     * @throws InvalidConfigException
348
     */
349 12
    private function validateDefinitionTags(mixed $tags): void
350
    {
351 12
        if (!is_array($tags)) {
352 1
            throw new InvalidConfigException(
353 1
                sprintf(
354
                    'Invalid definition: tags should be array of strings, %s given.',
355 1
                    get_debug_type($tags)
356
                )
357
            );
358
        }
359
360 11
        foreach ($tags as $tag) {
361 11
            if (!is_string($tag)) {
362 1
                throw new InvalidConfigException('Invalid tag. Expected a string, got ' . var_export($tag, true) . '.');
363
            }
364
        }
365
    }
366
367
    /**
368
     * @throws InvalidConfigException
369
     */
370 8
    private function validateDefinitionReset(mixed $reset): void
371
    {
372 8
        if (!$reset instanceof Closure) {
373 1
            throw new InvalidConfigException(
374 1
                sprintf(
375
                    'Invalid definition: "reset" should be closure, %s given.',
376 1
                    get_debug_type($reset)
377
                )
378
            );
379
        }
380
    }
381
382
    /**
383
     * @throws InvalidConfigException
384
     */
385 139
    private function setTags(array $tags): void
386
    {
387 139
        if ($this->validate) {
388 139
            foreach ($tags as $tag => $services) {
389 5
                if (!is_string($tag)) {
390 1
                    throw new InvalidConfigException(
391 1
                        sprintf(
392
                            'Invalid tags configuration: tag should be string, %s given.',
393
                            $tag
394
                        )
395
                    );
396
                }
397 4
                if (!is_array($services)) {
398 1
                    throw new InvalidConfigException(
399 1
                        sprintf(
400
                            'Invalid tags configuration: tag should contain array of service IDs, %s given.',
401 1
                            get_debug_type($services)
402
                        )
403
                    );
404
                }
405
                /** @var mixed $service */
406 3
                foreach ($services as $service) {
407 3
                    if (!is_string($service)) {
408 1
                        throw new InvalidConfigException(
409 1
                            sprintf(
410
                                'Invalid tags configuration: service should be defined as class string, %s given.',
411 1
                                get_debug_type($service)
412
                            )
413
                        );
414
                    }
415
                }
416
            }
417
        }
418
        /** @psalm-var array<string, list<string>> $tags */
419
420 136
        $this->tags = $tags;
421
    }
422
423
    /**
424
     * @psalm-param string[] $tags
425
     */
426 9
    private function setDefinitionTags(string $id, array $tags): void
427
    {
428 9
        foreach ($tags as $tag) {
429 9
            if (!isset($this->tags[$tag]) || !in_array($id, $this->tags[$tag], true)) {
430 9
                $this->tags[$tag][] = $id;
431
            }
432
        }
433
    }
434
435 7
    private function setDefinitionResetter(string $id, Closure $resetter): void
436
    {
437 7
        $this->resetters[$id] = $resetter;
438
    }
439
440
    /**
441
     * Add definition to storage.
442
     *
443
     * @see $definitions
444
     *
445
     * @param string $id ID to set definition for.
446
     * @param mixed|object $definition Definition to set.
447
     */
448 103
    private function addDefinitionToStorage(string $id, $definition): void
449
    {
450 103
        $this->definitions->set($id, $definition);
451
452 103
        if ($id === StateResetter::class) {
453 5
            $this->useResettersFromMeta = false;
454
        }
455
    }
456
457
    /**
458
     * Creates new instance by either interface name or alias.
459
     *
460
     * @param string $id The interface or an alias name that was previously registered.
461
     *
462
     * @throws CircularReferenceException
463
     * @throws InvalidConfigException
464
     * @throws NotFoundException
465
     *
466
     * @return mixed|object New built instance of the specified class.
467
     *
468
     * @internal
469
     */
470 104
    private function build(string $id)
471
    {
472 104
        if (TagHelper::isTagAlias($id)) {
473 10
            return $this->getTaggedServices($id);
474
        }
475
476 103
        if (isset($this->building[$id])) {
477 94
            if ($id === ContainerInterface::class) {
478 94
                return $this;
479
            }
480 4
            throw new CircularReferenceException(sprintf(
481
                'Circular reference to "%s" detected while building: %s.',
482
                $id,
483 4
                implode(', ', array_keys($this->building))
484
            ));
485
        }
486
487 103
        $this->building[$id] = 1;
488
        try {
489
            /** @var mixed $object */
490 103
            $object = $this->buildInternal($id);
491
        } finally {
492 103
            unset($this->building[$id]);
493
        }
494
495 94
        return $object;
496
    }
497
498 10
    private function getTaggedServices(string $tagAlias): array
499
    {
500 10
        $tag = TagHelper::extractTagFromAlias($tagAlias);
501 10
        $services = [];
502 10
        if (isset($this->tags[$tag])) {
503 9
            foreach ($this->tags[$tag] as $service) {
504
                /** @var mixed */
505 9
                $services[] = $this->get($service);
506
            }
507
        }
508
509 10
        return $services;
510
    }
511
512
    /**
513
     * @throws InvalidConfigException
514
     * @throws NotFoundException
515
     *
516
     * @return mixed|object
517
     */
518 103
    private function buildInternal(string $id)
519
    {
520 103
        if ($this->definitions->has($id)) {
521 94
            $definition = DefinitionNormalizer::normalize($this->definitions->get($id), $id);
522
523 94
            return $definition->resolve($this->get(ContainerInterface::class));
524
        }
525
526 11
        throw new NotFoundException($id, $this->definitions->getBuildStack());
527
    }
528
529
    /**
530
     * @throws CircularReferenceException
531
     * @throws InvalidConfigException
532
     */
533 127
    private function addProviders(array $providers): void
534
    {
535 127
        $extensions = [];
536
        /** @var mixed $provider */
537 127
        foreach ($providers as $provider) {
538 15
            $providerInstance = $this->buildProvider($provider);
539 13
            $extensions[] = $providerInstance->getExtensions();
540 13
            $this->addDefinitions($providerInstance->getDefinitions());
541
        }
542
543 125
        foreach ($extensions as $providerExtensions) {
544
            /** @var mixed $extension */
545 13
            foreach ($providerExtensions as $id => $extension) {
546 10
                if (!is_string($id)) {
547 1
                    throw new InvalidConfigException(
548 1
                        sprintf('Extension key must be a service ID as string, %s given.', $id)
549
                    );
550
                }
551
552 9
                if ($id === ContainerInterface::class) {
553 1
                    throw new InvalidConfigException('ContainerInterface extensions are not allowed.');
554
                }
555
556 8
                if (!$this->definitions->has($id)) {
557 1
                    throw new InvalidConfigException("Extended service \"$id\" doesn't exist.");
558
                }
559
560 8
                if (!is_callable($extension)) {
561 1
                    throw new InvalidConfigException(
562 1
                        sprintf(
563
                            'Extension of service should be callable, %s given.',
564 1
                            get_debug_type($extension)
565
                        )
566
                    );
567
                }
568
569
                /** @var mixed $definition */
570 7
                $definition = $this->definitions->get($id);
571 7
                if (!$definition instanceof ExtensibleService) {
572 7
                    $definition = new ExtensibleService($definition, $id);
573 7
                    $this->addDefinitionToStorage($id, $definition);
574
                }
575
576 7
                $definition->addExtension($extension);
577
            }
578
        }
579
    }
580
581
    /**
582
     * Builds service provider by definition.
583
     *
584
     * @param mixed $provider Class name or instance of provider.
585
     *
586
     * @throws InvalidConfigException If provider argument is not valid.
587
     *
588
     * @return ServiceProviderInterface Instance of service provider.
589
     */
590 15
    private function buildProvider(mixed $provider): ServiceProviderInterface
591
    {
592 15
        if ($this->validate && !(is_string($provider) || $provider instanceof ServiceProviderInterface)) {
593 1
            throw new InvalidConfigException(
594 1
                sprintf(
595
                    'Service provider should be a class name or an instance of %s. %s given.',
596
                    ServiceProviderInterface::class,
597 1
                    get_debug_type($provider)
598
                )
599
            );
600
        }
601
602
        /**
603
         * @psalm-suppress MixedMethodCall Service provider defined as class string
604
         * should container public constructor, otherwise throws error.
605
         */
606 14
        $providerInstance = is_object($provider) ? $provider : new $provider();
607 14
        if (!$providerInstance instanceof ServiceProviderInterface) {
608 1
            throw new InvalidConfigException(
609 1
                sprintf(
610
                    'Service provider should be an instance of %s. %s given.',
611
                    ServiceProviderInterface::class,
612 1
                    get_debug_type($providerInstance)
613
                )
614
            );
615
        }
616
617 13
        return $providerInstance;
618
    }
619
620 5
    private function decorateLazy(string $id, $definition): DefinitionInterface
621
    {
622 5
        $factory = $this->getLazyLoadingValueHolderFactory();
623 5
        if (class_exists($id) || interface_exists($id)) {
624 4
            $class = $id;
625 1
        } elseif (is_array($definition)) {
626 1
            $class = $definition['class'];
627
        } else {
628
            throw new RuntimeException(
629
                sprintf(
630
                    'Could not handle definition type "%s" with definition class "%s"',
631
                    get_debug_type($definition),
632
                    $id,
633
                )
634
            );
635
        }
636
637 5
        return new LazyDefinitionDecorator($factory, $definition, $class);
638
    }
639
640 5
    private function getLazyLoadingValueHolderFactory(): LazyLoadingValueHolderFactory
641
    {
642 5
        if (!class_exists(LazyLoadingValueHolderFactory::class)) {
643
            throw new RuntimeException('You should install `ocramius/proxy-manager` if you want to use lazy services.');
644
        }
645 5
        return $this->lazyFactory ??= new LazyLoadingValueHolderFactory();
646
    }
647
}
648