Passed
Pull Request — master (#233)
by Dmitriy
02:21
created

Container::addProviderDefinitions()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 7
nc 4
nop 1
dl 0
loc 10
ccs 7
cts 7
cp 1
crap 4
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 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
    private DependencyResolver $dependencyResolver;
64
65
    /**
66
     * Container constructor.
67
     *
68
     * @param array $definitions Definitions to put into container.
69
     * @param array $providers Service providers to get definitions from.
70
     * @param ContainerInterface|null $rootContainer Root container to delegate
71
     * lookup to when resolving dependencies. If provided the current container
72
     * is no longer queried for dependencies.
73
     *
74
     * @throws InvalidConfigException
75
     */
76 88
    public function __construct(
77
        array $definitions = [],
78
        array $providers = [],
79
        array $tags = [],
80
        bool $validate = true
81
    ) {
82 88
        $this->tags = $tags;
83 88
        $this->validate = $validate;
84 88
        $this->setDefaultDefinitions();
85 88
        $this->setMultiple($definitions);
86 82
        $this->addProviders($providers);
87 82
    }
88
89
    /**
90
     * Returns a value indicating whether the container has the definition of the specified name.
91
     *
92
     * @param string $id class name, interface name or alias name
93
     *
94
     * @return bool whether the container is able to provide instance of class specified.
95
     *
96
     * @see set()
97
     */
98 23
    public function has($id): bool
99
    {
100 23
        if ($this->isTagAlias($id)) {
101 2
            $tag = substr($id, 4);
102 2
            return isset($this->tags[$tag]);
103
        }
104
105 21
        return isset($this->definitions[$id]) || class_exists($id);
106
    }
107
108
    /**
109
     * Returns an instance by either interface name or alias.
110
     *
111
     * Same instance of the class will be returned each time this method is called.
112
     *
113
     * @param string $id The interface or an alias name that was previously registered.
114
     *
115
     * @throws CircularReferenceException
116
     * @throws InvalidConfigException
117
     * @throws NotFoundException
118
     * @throws NotInstantiableException
119
     *
120
     * @return mixed|object An instance of the requested interface.
121
     *
122
     * @psalm-template T
123
     * @psalm-param string|class-string<T> $id
124
     * @psalm-return ($id is class-string ? T : mixed)
125
     */
126 78
    public function get($id)
127
    {
128 78
        if ($id === StateResetter::class && !isset($this->definitions[$id])) {
129 4
            $resetters = [];
130 4
            foreach ($this->resetters as $serviceId => $callback) {
131 4
                if (isset($this->instances[$serviceId])) {
132 4
                    $resetters[] = $callback->bindTo($this->instances[$serviceId], get_class($this->instances[$serviceId]));
133
                }
134
            }
135 4
            return new StateResetter($resetters, $this);
136
        }
137
138 78
        if (!array_key_exists($id, $this->instances)) {
139 78
            $this->instances[$id] = $this->build($id);
140
        }
141
142 76
        return $this->instances[$id];
143
    }
144
145
    /**
146
     * Sets a definition to the container. Definition may be defined multiple ways.
147
     *
148
     * @param string $id
149
     * @param mixed $definition
150
     *
151
     * @throws InvalidConfigException
152
     *
153
     * @see `DefinitionNormalizer::normalize()`
154
     */
155 88
    protected function set(string $id, $definition): void
156
    {
157 88
        [$definition, $meta] = DefinitionParser::parse($definition);
158 88
        if ($this->validate) {
159 88
            $this->validateDefinition($definition, $id);
160 88
            $this->validateMeta($meta);
161
        }
162
163 88
        if (isset($meta[self::META_TAGS])) {
164 8
            if ($this->validate) {
165 8
                $this->validateTags($meta[self::META_TAGS]);
166
            }
167 8
            $this->setTags($id, $meta[self::META_TAGS]);
168
        }
169 88
        if (isset($meta[self::META_RESET])) {
170 5
            $this->setResetter($id, $meta[self::META_RESET]);
171
        }
172
173 88
        unset($this->instances[$id]);
174 88
        $this->definitions[$id] = $definition;
175 88
    }
176
177
    /**
178
     * Sets multiple definitions at once.
179
     *
180
     * @param array $config definitions indexed by their ids
181
     *
182
     * @throws InvalidConfigException
183
     */
184 88
    protected function setMultiple(array $config): void
185
    {
186 88
        foreach ($config as $id => $definition) {
187 88
            if ($this->validate && !is_string($id)) {
188 1
                throw new InvalidConfigException(sprintf('Key must be a string. %s given.', $this->getVariableType($id)));
189
            }
190 88
            $this->set($id, $definition);
191
        }
192 88
    }
193
194 88
    private function setDefaultDefinitions(): void
195
    {
196 88
        $this->setMultiple([
197 88
            ContainerInterface::class => $this,
198 88
            Injector::class => new Injector($this),
199
        ]);
200 88
    }
201
202
    /**
203
     * @param mixed $definition
204
     *
205
     * @throws InvalidConfigException
206
     */
207 88
    private function validateDefinition($definition, ?string $id = null): void
208
    {
209 88
        if (is_array($definition) && isset($definition[DefinitionParser::IS_PREPARED_ARRAY_DEFINITION_DATA])) {
210 36
            [$class, $constructorArguments, $methodsAndProperties] = $definition;
211 36
            $definition = array_merge(
212 36
                $class === null ? [] : [ArrayDefinition::CLASS_NAME => $class],
213 36
                [ArrayDefinition::CONSTRUCTOR => $constructorArguments],
214
                $methodsAndProperties,
215
            );
216
        }
217
218 88
        if ($definition instanceof ExtensibleService) {
219
            throw new InvalidConfigException('Invalid definition. ExtensibleService is only allowed in provider extensions.');
220
        }
221
222 88
        DefinitionValidator::validate($definition, $id);
223 88
    }
224
225
    /**
226
     * @throws InvalidConfigException
227
     */
228 88
    private function validateMeta(array $meta): void
229
    {
230 88
        foreach ($meta as $key => $_value) {
231 16
            if (!in_array($key, self::ALLOWED_META, true)) {
232 3
                throw new InvalidConfigException(
233 3
                    sprintf(
234 3
                        'Invalid definition: metadata "%s" is not allowed. Did you mean "%s()" or "$%s"?',
235
                        $key,
236
                        $key,
237
                        $key,
238
                    )
239
                );
240
            }
241
        }
242 88
    }
243
244 8
    private function validateTags(array $tags): void
245
    {
246 8
        foreach ($tags as $tag) {
247 8
            if (!is_string($tag)) {
248
                throw new InvalidConfigException('Invalid tag. Expected a string, got ' . var_export($tag, true) . '.');
249
            }
250
        }
251 8
    }
252
253 8
    private function setTags(string $id, array $tags): void
254
    {
255 8
        foreach ($tags as $tag) {
256 8
            if (!isset($this->tags[$tag]) || !in_array($id, $this->tags[$tag], true)) {
257 8
                $this->tags[$tag][] = $id;
258
            }
259
        }
260 8
    }
261
262 4
    private function setResetter(string $id, Closure $resetter): void
263
    {
264 4
        $this->resetters[$id] = $resetter;
265 4
    }
266
267
    /**
268
     * Creates new instance by either interface name or alias.
269
     *
270
     * @param string $id The interface or an alias name that was previously registered.
271
     *
272
     * @throws CircularReferenceException
273
     * @throws InvalidConfigException
274
     * @throws NotFoundException
275
     *
276
     * @return mixed|object New built instance of the specified class.
277
     *
278
     * @internal
279
     */
280 78
    private function build(string $id)
281
    {
282 78
        if ($this->isTagAlias($id)) {
283 9
            return $this->getTaggedServices($id);
284
        }
285
286 77
        if (isset($this->building[$id])) {
287 75
            if ($id === ContainerInterface::class) {
288 75
                return $this;
289
            }
290 7
            throw new CircularReferenceException(sprintf(
291 7
                'Circular reference to "%s" detected while building: %s.',
292
                $id,
293 7
                implode(',', array_keys($this->building))
294
            ));
295
        }
296
297 77
        $this->building[$id] = 1;
298
        try {
299 77
            $object = $this->buildInternal($id);
300 75
        } finally {
301 77
            unset($this->building[$id]);
302
        }
303
304 75
        return $object;
305
    }
306
307 82
    private function isTagAlias(string $id): bool
308
    {
309 82
        return strpos($id, 'tag@') === 0;
310
    }
311
312 9
    private function getTaggedServices(string $tagAlias): array
313
    {
314 9
        $tag = substr($tagAlias, 4);
315 9
        $services = [];
316 9
        if (isset($this->tags[$tag])) {
317 8
            foreach ($this->tags[$tag] as $service) {
318 8
                $services[] = $this->get($service);
319
            }
320
        }
321
322 9
        return $services;
323
    }
324
325
    /**
326
     * @param mixed $definition
327
     */
328 75
    private function processDefinition($definition): void
329
    {
330 75
        if ($definition instanceof DeferredServiceProviderInterface) {
331 1
            $definitions = $definition->getDefinitions();
332 1
            foreach ($definitions as $id => $def) {
333 1
                $this->set($id, $def);
334
            }
335
        }
336 75
    }
337
338
    /**
339
     * @param string $id
340
     *
341
     * @throws InvalidConfigException
342
     * @throws NotFoundException
343
     *
344
     * @return mixed|object
345
     */
346 77
    private function buildInternal(string $id)
347
    {
348 77
        if (!isset($this->definitions[$id])) {
349 45
            return $this->buildPrimitive($id);
350
        }
351 75
        $this->processDefinition($this->definitions[$id]);
352 75
        $definition = DefinitionNormalizer::normalize($this->definitions[$id], $id);
353 75
        $this->dependencyResolver = $this->dependencyResolver ?? new DependencyResolver($this->get(ContainerInterface::class));
354
355 75
        return $definition->resolve($this->dependencyResolver);
356
    }
357
358
    /**
359
     * @param string $class
360
     *
361
     * @throws InvalidConfigException
362
     * @throws NotFoundException
363
     *
364
     * @return mixed|object
365
     */
366 45
    private function buildPrimitive(string $class)
367
    {
368 45
        if (class_exists($class)) {
369 43
            $definition = ArrayDefinition::fromPreparedData($class);
370 43
            $this->dependencyResolver = $this->dependencyResolver ?? new DependencyResolver($this->get(ContainerInterface::class));
371
372 43
            return $definition->resolve($this->dependencyResolver);
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
            if (!is_string($provider)) {
441 1
                new InvalidConfigException(
442 1
                    sprintf(
443 1
                        'Service provider should be a class name or an instance of %s. %s given.',
444 1
                        ServiceProviderInterface::class,
445 1
                        $this->getVariableType($provider)
446
                    )
447
                );
448
            }
449
        }
450
451 3
        $providerInstance = is_object($provider) ? $provider : new $provider();
452 3
        if (!$providerInstance instanceof ServiceProviderInterface) {
453
            new InvalidConfigException(
454
                sprintf(
455
                    'Service provider should be an instance of %s. %s given.',
456
                    ServiceProviderInterface::class,
457
                    $this->getVariableType($providerInstance)
458
                )
459
            );
460
        }
461
462 3
        return $providerInstance;
463
    }
464
465
    /**
466
     * @param mixed $variable
467
     */
468 2
    private function getVariableType($variable): string
469
    {
470 2
        if (is_object($variable)) {
471 1
            return get_class($variable);
472
        }
473
474 1
        return gettype($variable);
475
    }
476
}
477