Passed
Pull Request — master (#233)
by Dmitriy
07:13
created

Container::addProviders()   A

Complexity

Conditions 6
Paths 10

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6.0163

Importance

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