Passed
Push — resetter ( e6dae4 )
by Sergei
02:32
created

Container::setDefinitions()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 2
nop 1
dl 0
loc 10
ccs 5
cts 5
cp 1
crap 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Di;
6
7
use Closure;
8
use InvalidArgumentException;
9
use Psr\Container\ContainerInterface;
10
use Yiisoft\Definitions\ArrayDefinition;
11
use Yiisoft\Definitions\Exception\CircularReferenceException;
12
use Yiisoft\Definitions\Exception\InvalidConfigException;
13
use Yiisoft\Definitions\Exception\NotInstantiableException;
14
use Yiisoft\Definitions\Helpers\DefinitionValidator;
15
use Yiisoft\Definitions\DefinitionStorage;
16
17
use function array_key_exists;
18
use function array_keys;
19
use function get_class;
20
use function gettype;
21
use function implode;
22
use function in_array;
23
use function is_array;
24
use function is_object;
25
use function is_string;
26
27
/**
28
 * Container implements a [dependency injection](http://en.wikipedia.org/wiki/Dependency_injection) container.
29
 */
30
final class Container implements ContainerInterface
31
{
32
    private const META_TAGS = 'tags';
33
    private const META_RESET = 'reset';
34
    private const ALLOWED_META = [self::META_TAGS, self::META_RESET];
35
36
    /**
37
     * @var DefinitionStorage Storage of object definitions.
38
     */
39
    private DefinitionStorage $definitions;
40
    /**
41
     * @var array Used to collect IDs of objects instantiated during build
42
     * to detect circular references.
43
     */
44
    private array $building = [];
45
46
    /**
47
     * @var bool $validate If definitions should be validated.
48
     */
49
    private bool $validate;
50
51
    /**
52
     * @var object[]
53
     */
54
    private array $instances = [];
55
56
    private CompositeContainer $delegates;
57
58
    /**
59
     * @var array Tagged service IDs. The structure is `['tagID' => ['service1', 'service2']]`.
60
     */
61
    private array $tags;
62
63
    private array $resetters = [];
64
65
    /**
66
     * Container constructor.
67
     *
68
     * @param ContainerConfigInterface $config Container configuration.
69
     *
70
     * @throws InvalidConfigException
71
     * @psalm-suppress PropertyNotSetInConstructor
72
     */
73 117
    public function __construct(ContainerConfigInterface $config)
74
    {
75 117
        $this->definitions = new DefinitionStorage([], $config->useStrictMode());
76 117
        $this->tags = $config->getTags();
77 117
        $this->validate = $config->shouldValidate();
78 117
        $this->setDefaultDefinitions();
79 117
        $this->setDefinitions($config->getDefinitions());
80 108
        $this->addProviders($config->getProviders());
81 104
        $this->setDelegates($config->getDelegates());
82 102
    }
83
84
    /**
85
     * Returns a value indicating whether the container has the definition of the specified name.
86
     *
87
     * @param string $id Class name, interface name or alias name.
88
     *
89
     * @return bool Whether the container is able to provide instance of class specified.
90
     *
91
     * @see set()
92
     */
93 39
    public function has($id): bool
94
    {
95
        /** @psalm-suppress  DocblockTypeContradiction */
96 39
        if (!is_string($id)) {
0 ignored issues
show
introduced by
The condition is_string($id) is always true.
Loading history...
97 1
            return false;
98
        }
99
100 38
        if ($this->isTagAlias($id)) {
101 3
            $tag = substr($id, 4);
102 3
            return isset($this->tags[$tag]);
103
        }
104
105
        try {
106 35
            return $this->definitions->has($id);
107 3
        } catch (CircularReferenceException $e) {
108 3
            return true;
109
        }
110
    }
111
112
    /**
113
     * Returns an instance by either interface name or alias.
114
     *
115
     * Same instance of the class will be returned each time this method is called.
116
     *
117
     * @param string $id The interface or an alias name that was previously registered.
118
     *
119
     * @throws CircularReferenceException
120
     * @throws InvalidConfigException
121
     * @throws NotFoundException
122
     * @throws NotInstantiableException
123
     *
124
     * @return mixed|object An instance of the requested interface.
125
     *
126
     * @psalm-template T
127
     * @psalm-param string|class-string<T> $id
128
     * @psalm-return ($id is class-string ? T : mixed)
129
     */
130 90
    public function get($id)
131
    {
132
        /** @psalm-suppress TypeDoesNotContainType */
133 90
        if (!is_string($id)) {
0 ignored issues
show
introduced by
The condition is_string($id) is always true.
Loading history...
134 1
            throw new InvalidArgumentException("Id must be a string, {$this->getVariableType($id)} given.");
135
        }
136
137 89
        if (!array_key_exists($id, $this->instances)) {
138
            try {
139 89
                $this->instances[$id] = $this->build($id);
140 18
            } catch (NotFoundException $e) {
141 9
                if (!$this->delegates->has($id)) {
142 7
                    throw $e;
143
                }
144
145 2
                return $this->delegates->get($id);
146
            }
147
        }
148
149 80
        if ($id === StateResetter::class && $this->definitions->get($id) === StateResetter::class) {
150 5
            $resetters = [];
151 5
            foreach ($this->resetters as $serviceId => $callback) {
152 5
                if (isset($this->instances[$serviceId])) {
153 5
                    $resetters[$serviceId] = $callback;
154
                }
155
            }
156 5
            if ($this->delegates->has(StateResetter::class)) {
157 1
                $resetters[] = $this->delegates->get(StateResetter::class);
158
            }
159 5
            $this->instances[$id]->setResetters($resetters);
160
        }
161
162 80
        return $this->instances[$id];
163
    }
164
165
    /**
166
     * Sets a definition to the container. Definition may be defined multiple ways.
167
     *
168
     * @param string $id ID to set definition for.
169
     * @param mixed $definition Definition to set.
170
     *
171
     * @throws InvalidConfigException
172
     *
173
     * @see DefinitionNormalizer::normalize()
174
     */
175 117
    private function set(string $id, $definition): void
176
    {
177 117
        [$definition, $meta] = DefinitionParser::parse($definition);
178 117
        if ($this->validate) {
179 117
            $this->validateDefinition($definition, $id);
180 117
            $this->validateMeta($meta);
181
        }
182
183 117
        if (isset($meta[self::META_TAGS])) {
184 10
            if ($this->validate) {
185 10
                $this->validateTags($meta[self::META_TAGS]);
186
            }
187 9
            $this->setTags($id, $meta[self::META_TAGS]);
188
        }
189 117
        if (isset($meta[self::META_RESET])) {
190 6
            $this->setResetter($id, $meta[self::META_RESET]);
191
        }
192
193 117
        unset($this->instances[$id]);
194 117
        $this->definitions->set($id, $definition);
195 117
    }
196
197
    /**
198
     * Sets multiple definitions at once.
199
     *
200
     * @param array $config Definitions indexed by their IDs.
201
     *
202
     * @throws InvalidConfigException
203
     */
204 117
    private function setMultiple(array $config): void
205
    {
206 117
        foreach ($config as $id => $definition) {
207 117
            if ($this->validate && !is_string($id)) {
208 1
                throw new InvalidConfigException(sprintf('Key must be a string. %s given.', $this->getVariableType($id)));
209
            }
210 117
            $this->set($id, $definition);
211
        }
212 117
    }
213
214 117
    private function setDefaultDefinitions(): void
215
    {
216 117
        $this->setMultiple([
217 117
            ContainerInterface::class => $this,
218
            StateResetter::class => StateResetter::class,
219
        ]);
220 117
    }
221
222 117
    private function setDefinitions(array $definitions): void
223
    {
224 117
        if (isset($definitions[StateResetter::class]) && $definitions[StateResetter::class] === StateResetter::class) {
225 1
            throw new InvalidArgumentException(
226
                'Container contain standard state resetter definition ' .
227
                '"StateResetter::class => StateResetter::class" by default. ' .
228 1
                'Use array or callable definition for override default state resetter.'
229
            );
230
        }
231 116
        $this->setMultiple($definitions);
232 108
    }
233
234
    /**
235
     * Set container delegates.
236
     *
237
     * Each delegate must is a callable in format "function (ContainerInterface $container): ContainerInterface".
238
     * The container instance returned is used in case a service can not be found in primary container.
239
     *
240
     * @param array $delegates
241
     *
242
     * @throws InvalidConfigException
243
     */
244 104
    private function setDelegates(array $delegates): void
245
    {
246 104
        $this->delegates = new CompositeContainer();
247 104
        foreach ($delegates as $delegate) {
248 4
            if (!$delegate instanceof Closure) {
249 1
                throw new InvalidConfigException(
250 1
                    'Delegate must be callable in format "function (ContainerInterface $container): ContainerInterface".'
251
                );
252
            }
253
254 3
            $delegate = $delegate($this);
255
256 3
            if (!$delegate instanceof ContainerInterface) {
257 1
                throw new InvalidConfigException(
258 1
                    'Delegate callable must return an object that implements ContainerInterface.'
259
                );
260
            }
261
262 2
            $this->delegates->attach($delegate);
263
        }
264 102
        $this->definitions->setDelegateContainer($this->delegates);
265 102
    }
266
267
    /**
268
     * @param mixed $definition Definition to validate.
269
     * @param string|null $id ID of the definition to validate.
270
     *
271
     * @throws InvalidConfigException
272
     */
273 117
    private function validateDefinition($definition, ?string $id = null): void
274
    {
275 117
        if (is_array($definition) && isset($definition[DefinitionParser::IS_PREPARED_ARRAY_DEFINITION_DATA])) {
276 39
            $class = $definition['class'];
277 39
            $constructorArguments = $definition['__construct()'];
278 39
            $methodsAndProperties = $definition['methodsAndProperties'];
279 39
            $definition = array_merge(
280 39
                $class === null ? [] : [ArrayDefinition::CLASS_NAME => $class],
281 39
                [ArrayDefinition::CONSTRUCTOR => $constructorArguments],
282
                $methodsAndProperties,
283
            );
284
        }
285
286 117
        if ($definition instanceof ExtensibleService) {
287 1
            throw new InvalidConfigException('Invalid definition. ExtensibleService is only allowed in provider extensions.');
288
        }
289
290 117
        DefinitionValidator::validate($definition, $id);
291 117
    }
292
293
    /**
294
     * @throws InvalidConfigException
295
     */
296 117
    private function validateMeta(array $meta): void
297
    {
298 117
        foreach ($meta as $key => $_value) {
299 19
            if (!in_array($key, self::ALLOWED_META, true)) {
300 3
                throw new InvalidConfigException(
301 3
                    sprintf(
302 3
                        'Invalid definition: metadata "%s" is not allowed. Did you mean "%s()" or "$%s"?',
303
                        $key,
304
                        $key,
305
                        $key,
306
                    )
307
                );
308
            }
309
        }
310 117
    }
311
312 10
    private function validateTags(array $tags): void
313
    {
314 10
        foreach ($tags as $tag) {
315 10
            if (!is_string($tag)) {
316 1
                throw new InvalidConfigException('Invalid tag. Expected a string, got ' . var_export($tag, true) . '.');
317
            }
318
        }
319 9
    }
320
321 9
    private function setTags(string $id, array $tags): void
322
    {
323 9
        foreach ($tags as $tag) {
324 9
            if (!isset($this->tags[$tag]) || !in_array($id, $this->tags[$tag], true)) {
325 9
                $this->tags[$tag][] = $id;
326
            }
327
        }
328 9
    }
329
330 5
    private function setResetter(string $id, Closure $resetter): void
331
    {
332 5
        $this->resetters[$id] = $resetter;
333 5
    }
334
335
    /**
336
     * Creates new instance by either interface name or alias.
337
     *
338
     * @param string $id The interface or an alias name that was previously registered.
339
     *
340
     * @throws CircularReferenceException
341
     * @throws InvalidConfigException
342
     * @throws NotFoundException
343
     *
344
     * @return mixed|object New built instance of the specified class.
345
     *
346
     * @internal
347
     */
348 89
    private function build(string $id)
349
    {
350 89
        if ($this->isTagAlias($id)) {
351 10
            return $this->getTaggedServices($id);
352
        }
353
354 88
        if (isset($this->building[$id])) {
355 79
            if ($id === ContainerInterface::class) {
356 79
                return $this;
357
            }
358 4
            throw new CircularReferenceException(sprintf(
359 4
                'Circular reference to "%s" detected while building: %s.',
360
                $id,
361 4
                implode(', ', array_keys($this->building))
362
            ));
363
        }
364
365 88
        $this->building[$id] = 1;
366
        try {
367 88
            $object = $this->buildInternal($id);
368 79
        } finally {
369 88
            unset($this->building[$id]);
370
        }
371
372 79
        return $object;
373
    }
374
375 100
    private function isTagAlias(string $id): bool
376
    {
377 100
        return strncmp($id, 'tag@', 4) === 0;
378
    }
379
380 10
    private function getTaggedServices(string $tagAlias): array
381
    {
382 10
        $tag = substr($tagAlias, 4);
383 10
        $services = [];
384 10
        if (isset($this->tags[$tag])) {
385 9
            foreach ($this->tags[$tag] as $service) {
386 9
                $services[] = $this->get($service);
387
            }
388
        }
389
390 10
        return $services;
391
    }
392
393
    /**
394
     * @param string $id
395
     *
396
     * @throws InvalidConfigException
397
     * @throws NotFoundException
398
     *
399
     * @return mixed|object
400
     */
401 88
    private function buildInternal(string $id)
402
    {
403 88
        if ($this->definitions->has($id)) {
404 79
            $definition = DefinitionNormalizer::normalize($this->definitions->get($id), $id);
405
406 79
            return $definition->resolve($this->get(ContainerInterface::class));
407
        }
408
409 9
        throw new NotFoundException($id, $this->definitions->getBuildStack());
410
    }
411
412 108
    private function addProviders(array $providers): void
413
    {
414 108
        $extensions = [];
415 108
        foreach ($providers as $provider) {
416 9
            $providerInstance = $this->buildProvider($provider);
417 7
            $extensions[] = $providerInstance->getExtensions();
418 7
            $this->addProviderDefinitions($providerInstance);
419
        }
420
421 106
        foreach ($extensions as $providerExtensions) {
422 7
            foreach ($providerExtensions as $id => $extension) {
423 6
                if ($id === ContainerInterface::class) {
424 1
                    throw new InvalidConfigException('ContainerInterface extensions are not allowed.');
425
                }
426
427 5
                if (!$this->definitions->has($id)) {
428 1
                    throw new InvalidConfigException("Extended service \"$id\" doesn't exist.");
429
                }
430
431 5
                $definition = $this->definitions->get($id);
432 5
                if (!$definition instanceof ExtensibleService) {
433 5
                    $definition = new ExtensibleService($definition);
434 5
                    $this->definitions->set($id, $definition);
435
                }
436
437 5
                $definition->addExtension($extension);
438
            }
439
        }
440 104
    }
441
442
    /**
443
     * Adds service provider definitions to the container.
444
     *
445
     * @param ServiceProviderInterface $provider Provider to get definitions from.
446
     *
447
     * @throws InvalidConfigException
448
     * @throws NotInstantiableException
449
     */
450 7
    private function addProviderDefinitions(ServiceProviderInterface $provider): void
451
    {
452 7
        $definitions = $provider->getDefinitions();
453 7
        $this->setMultiple($definitions);
454 7
    }
455
456
    /**
457
     * Builds service provider by definition.
458
     *
459
     * @param mixed $provider Class name or instance of provider.
460
     *
461
     * @throws InvalidConfigException If provider argument is not valid.
462
     *
463
     * @return ServiceProviderInterface Instance of service provider.
464
     *
465
     * @psalm-suppress MoreSpecificReturnType
466
     */
467 9
    private function buildProvider($provider): ServiceProviderInterface
468
    {
469 9
        if ($this->validate && !(is_string($provider) || $provider instanceof ServiceProviderInterface)) {
470 1
            throw new InvalidConfigException(
471 1
                sprintf(
472 1
                    'Service provider should be a class name or an instance of %s. %s given.',
473 1
                    ServiceProviderInterface::class,
474 1
                    $this->getVariableType($provider)
475
                )
476
            );
477
        }
478
479 8
        $providerInstance = is_object($provider) ? $provider : new $provider();
480 8
        if (!$providerInstance instanceof ServiceProviderInterface) {
481 1
            throw new InvalidConfigException(
482 1
                sprintf(
483 1
                    'Service provider should be an instance of %s. %s given.',
484 1
                    ServiceProviderInterface::class,
485 1
                    $this->getVariableType($providerInstance)
486
                )
487
            );
488
        }
489
490
        /**
491
         * @psalm-suppress LessSpecificReturnStatement
492
         */
493 7
        return $providerInstance;
494
    }
495
496
    /**
497
     * @param mixed $variable
498
     */
499 4
    private function getVariableType($variable): string
500
    {
501 4
        return is_object($variable) ? get_class($variable) : gettype($variable);
502
    }
503
}
504