Test Failed
Pull Request — master (#237)
by Sergei
02:23
created

Container::addProviderDefinitions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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