Passed
Push — resetter2 ( d6469b...878b81 )
by Sergei
07:24
created

Container::setDefaultDefinitions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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