Passed
Pull Request — master (#240)
by Dmitriy
02:51
created

Container::set()   A

Complexity

Conditions 5
Paths 12

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 5

Importance

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