Test Failed
Push — refactoring ( c1e666...b19607 )
by Sergei
02:36
created

Container   F

Complexity

Total Complexity 61

Size/Duplication

Total Lines 428
Duplicated Lines 0 %

Test Coverage

Coverage 99.22%

Importance

Changes 11
Bugs 2 Features 0
Metric Value
eloc 131
c 11
b 2
f 0
dl 0
loc 428
ccs 128
cts 129
cp 0.9922
rs 3.52
wmc 61

22 Methods

Rating   Name   Duplication   Size   Complexity  
A get() 0 17 6
A has() 0 8 3
A setTags() 0 5 4
A addProviders() 0 4 2
A set() 0 20 5
A validateTags() 0 5 3
A setDefaultDefinitions() 0 6 1
A buildProvider() 0 15 2
A setResetter() 0 3 1
A delegateLookup() 0 11 3
A build() 0 25 4
A validateMeta() 0 10 3
A processDefinition() 0 4 2
A buildInternal() 0 9 2
A isTagAlias() 0 3 1
A setMultiple() 0 7 4
A validateDefinition() 0 11 4
A getTaggedServices() 0 11 3
A getVariableType() 0 7 2
A buildPrimitive() 0 9 2
A __construct() 0 16 1
A addProvider() 0 10 3

How to fix   Complexity   

Complex Class

Complex classes like Container often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Container, and based on these observations, apply Extract Interface, too.

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;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Factory\Definition\DefinitionValidator was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
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 extends AbstractContainerConfigurator 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 ?CompositeContainer $rootContainer = null;
64
65
    /**
66
     * Container constructor.
67
     *
68
     * @param array $definitions Definitions to put into container.
69
     * @param ServiceProviderInterface[]|string[] $providers Service providers
70
     * to get definitions from.
71
     * @param ContainerInterface|null $rootContainer Root container to delegate
72 93
     * lookup to when resolving dependencies. If provided the current container
73
     * is no longer queried for dependencies.
74
     *
75
     * @throws InvalidConfigException
76
     */
77
    public function __construct(
78 93
        array $definitions = [],
79 93
        array $providers = [],
80 93
        array $tags = [],
81 93
        ContainerInterface $rootContainer = null,
82 93
        bool $validate = true
83 90
    ) {
84
        $this->tags = $tags;
85
        $this->validate = $validate;
86 88
        $this->delegateLookup($rootContainer);
87 88
        $this->setDefaultDefinitions();
88
        $this->setMultiple($definitions);
89
        $this->addProviders($providers);
90
91
        // Prevent circular reference to ContainerInterface
92
        $this->get(ContainerInterface::class);
93
    }
94
95
    /**
96
     * Returns a value indicating whether the container has the definition of the specified name.
97
     *
98 32
     * @param string $id class name, interface name or alias name
99
     *
100 32
     * @return bool whether the container is able to provide instance of class specified.
101 2
     *
102 2
     * @see set()
103
     */
104
    public function has($id): bool
105 30
    {
106
        if ($this->isTagAlias($id)) {
107
            $tag = substr($id, 4);
108
            return isset($this->tags[$tag]);
109
        }
110
111
        return isset($this->definitions[$id]) || class_exists($id);
112
    }
113
114
    /**
115
     * Returns an instance by either interface name or alias.
116
     *
117
     * Same instance of the class will be returned each time this method is called.
118
     *
119
     * @param string $id The interface or an alias name that was previously registered.
120
     *
121
     * @throws CircularReferenceException
122
     * @throws InvalidConfigException
123
     * @throws NotFoundException
124
     * @throws NotInstantiableException
125
     *
126 89
     * @return mixed|object An instance of the requested interface.
127
     *
128 89
     * @psalm-template T
129 4
     * @psalm-param string|class-string<T> $id
130 4
     * @psalm-return ($id is class-string ? T : mixed)
131 4
     */
132 4
    public function get($id)
133
    {
134
        if ($id === StateResetter::class && !isset($this->definitions[$id])) {
135 4
            $resetters = [];
136
            foreach ($this->resetters as $serviceId => $callback) {
137
                if (isset($this->instances[$serviceId])) {
138 89
                    $resetters[] = $callback->bindTo($this->instances[$serviceId], get_class($this->instances[$serviceId]));
139 89
                }
140
            }
141
            return new StateResetter($resetters, $this);
142 89
        }
143
144
        if (!array_key_exists($id, $this->instances)) {
145
            $this->instances[$id] = $this->build($id);
146
        }
147
148
        return $this->instances[$id];
149
    }
150 93
151
    /**
152 93
     * Delegate service lookup to another container.
153 93
     *
154
     * @param ContainerInterface $container
155 8
     */
156 8
    protected function delegateLookup(?ContainerInterface $container): void
157 8
    {
158
        if ($container === null) {
159
            return;
160 8
        }
161 8
        if ($this->rootContainer === null) {
162
            $this->rootContainer = new CompositeContainer();
163
            $this->setDefaultDefinitions();
164
        }
165
166
        $this->rootContainer->attach($container);
0 ignored issues
show
Bug introduced by
The method attach() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

166
        $this->rootContainer->/** @scrutinizer ignore-call */ 
167
                              attach($container);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
167
    }
168
169
    /**
170
     * Sets a definition to the container. Definition may be defined multiple ways.
171
     *
172
     * @param string $id
173 93
     * @param mixed $definition
174
     *
175 93
     * @throws InvalidConfigException
176
     *
177 93
     * @see `DefinitionNormalizer::normalize()`
178 93
     */
179 8
    protected function set(string $id, $definition): void
180 8
    {
181
        [$definition, $meta] = DefinitionParser::parse($definition);
182 93
        if ($this->validate) {
183 5
            $this->validateDefinition($definition, $id);
184
            $this->validateMeta($meta);
185
        }
186 93
187 93
        if (isset($meta[self::META_TAGS])) {
188 93
            if ($this->validate) {
189
                $this->validateTags($meta[self::META_TAGS]);
190
            }
191
            $this->setTags($id, $meta[self::META_TAGS]);
192
        }
193
        if (isset($meta[self::META_RESET])) {
194
            $this->setResetter($id, $meta[self::META_RESET]);
195
        }
196
197 93
        unset($this->instances[$id]);
198
        $this->definitions[$id] = $definition;
199 93
    }
200 93
201 1
    /**
202
     * Sets multiple definitions at once.
203 93
     *
204
     * @param array $config definitions indexed by their ids
205 93
     *
206
     * @throws InvalidConfigException
207 93
     */
208
    protected function setMultiple(array $config): void
209 93
    {
210 93
        foreach ($config as $id => $definition) {
211 93
            if ($this->validate && !is_string($id)) {
212 93
                throw new InvalidConfigException(sprintf('Key must be a string. %s given.', $this->getVariableType($id)));
213
            }
214 93
            $this->set($id, $definition);
215
        }
216 8
    }
217
218 8
    private function setDefaultDefinitions(): void
219 8
    {
220
        $container = $this->rootContainer ?? $this;
221
        $this->setMultiple([
222
            ContainerInterface::class => $container,
223 8
            Injector::class => new Injector($container),
224
        ]);
225 8
    }
226
227 8
    /**
228 8
     * @param mixed $definition
229 8
     *
230
     * @throws InvalidConfigException
231
     */
232 8
    private function validateDefinition($definition, ?string $id = null): void
233
    {
234 4
        if (is_array($definition) && isset($definition[DefinitionParser::IS_PREPARED_ARRAY_DEFINITION_DATA])) {
235
            [$class, $constructorArguments, $methodsAndProperties] = $definition;
236 4
            $definition = array_merge(
237 4
                $class === null ? [] : [ArrayDefinition::CLASS_NAME => $class],
238
                [ArrayDefinition::CONSTRUCTOR => $constructorArguments],
239
                $methodsAndProperties,
240
            );
241
        }
242
        DefinitionValidator::validate($definition, $id);
243
    }
244
245
    /**
246
     * @throws InvalidConfigException
247
     */
248
    private function validateMeta(array $meta): void
249
    {
250
        foreach ($meta as $key => $_value) {
251
            if (!in_array($key, self::ALLOWED_META, true)) {
252 89
                throw new InvalidConfigException(
253
                    sprintf(
254 89
                        'Invalid definition: metadata "%s" is not allowed. Did you mean "%s()" or "$%s"?',
255 9
                        $key,
256
                        $key,
257
                        $key,
258 89
                    )
259 9
                );
260 2
            }
261
        }
262 7
    }
263 7
264
    private function validateTags(array $tags): void
265 7
    {
266
        foreach ($tags as $tag) {
267
            if (!is_string($tag)) {
268
                throw new InvalidConfigException('Invalid tag. Expected a string, got ' . var_export($tag, true) . '.');
269 89
            }
270
        }
271 89
    }
272 89
273 89
    private function setTags(string $id, array $tags): void
274
    {
275
        foreach ($tags as $tag) {
276 89
            if (!isset($this->tags[$tag]) || !in_array($id, $this->tags[$tag], true)) {
277
                $this->tags[$tag][] = $id;
278
            }
279 89
        }
280
    }
281 89
282
    private function setResetter(string $id, Closure $resetter): void
283
    {
284 9
        $this->resetters[$id] = $resetter;
285
    }
286 9
287 9
    /**
288 9
     * Creates new instance by either interface name or alias.
289 8
     *
290 8
     * @param string $id The interface or an alias name that was previously registered.
291
     *
292
     * @throws CircularReferenceException
293
     * @throws InvalidConfigException
294 9
     * @throws NotFoundException
295
     *
296
     * @return mixed|object New built instance of the specified class.
297
     *
298
     * @internal
299
     */
300 89
    private function build(string $id)
301
    {
302 89
        if ($this->isTagAlias($id)) {
303 1
            return $this->getTaggedServices($id);
304
        }
305 89
306
        if (isset($this->building[$id])) {
307
            if ($id === ContainerInterface::class) {
308
                return $this;
309
            }
310
            throw new CircularReferenceException(sprintf(
311
                'Circular reference to "%s" detected while building: %s.',
312
                $id,
313
                implode(',', array_keys($this->building))
314
            ));
315 89
        }
316
317 89
        $this->building[$id] = 1;
318 51
        try {
319
            $object = $this->buildInternal($id);
320 89
        } finally {
321 89
            unset($this->building[$id]);
322
        }
323 89
324
        return $object;
325
    }
326
327
    private function isTagAlias(string $id): bool
328
    {
329
        return strpos($id, 'tag@') === 0;
330
    }
331
332
    private function getTaggedServices(string $tagAlias): array
333
    {
334 51
        $tag = substr($tagAlias, 4);
335
        $services = [];
336 51
        if (isset($this->tags[$tag])) {
337 49
            foreach ($this->tags[$tag] as $service) {
338
                $services[] = $this->get($service);
339 49
            }
340
        }
341
342 4
        return $services;
343
    }
344
345 90
    /**
346
     * @param mixed $definition
347 90
     */
348 6
    private function processDefinition($definition): void
349
    {
350 88
        if ($definition instanceof DeferredServiceProviderInterface) {
351
            $definition->register($this);
352
        }
353
    }
354
355
    /**
356
     * @param string $id
357
     *
358
     * @throws InvalidConfigException
359
     * @throws NotFoundException
360
     *
361
     * @return mixed|object
362
     */
363
    private function buildInternal(string $id)
364 6
    {
365
        if (!isset($this->definitions[$id])) {
366 6
            return $this->buildPrimitive($id);
367
        }
368 5
        $this->processDefinition($this->definitions[$id]);
369 1
        $definition = DefinitionNormalizer::normalize($this->definitions[$id], $id);
370 1
371
        return $definition->resolve($this->rootContainer ?? $this);
372
    }
373 4
374
    /**
375 4
     * @param string $class
376
     *
377
     * @throws InvalidConfigException
378
     * @throws NotFoundException
379
     *
380
     * @return mixed|object
381
     */
382
    private function buildPrimitive(string $class)
383
    {
384
        if (class_exists($class)) {
385
            $definition = ArrayDefinition::fromPreparedData($class);
0 ignored issues
show
Bug introduced by
The method fromPreparedData() does not exist on Yiisoft\Factory\Definition\ArrayDefinition. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

385
            /** @scrutinizer ignore-call */ 
386
            $definition = ArrayDefinition::fromPreparedData($class);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
386 6
387
            return $definition->resolve($this->rootContainer ?? $this);
388 6
        }
389 5
390 5
        throw new NotFoundException($class);
391 5
    }
392 5
393 5
    private function addProviders(array $providers): void
394
    {
395
        foreach ($providers as $provider) {
396
            $this->addProvider($provider);
397 5
        }
398
    }
399
400
    /**
401
     * Adds service provider to the container. Unless service provider is deferred
402
     * it would be immediately registered.
403 6
     *
404
     * @param mixed $providerDefinition
405 6
     *
406 5
     * @throws InvalidConfigException
407
     * @throws NotInstantiableException
408
     *
409 1
     * @see ServiceProviderInterface
410
     * @see DeferredServiceProviderInterface
411
     */
412
    private function addProvider($providerDefinition): void
413
    {
414
        $provider = $this->buildProvider($providerDefinition);
415
416
        if ($provider instanceof DeferredServiceProviderInterface) {
417
            foreach ($provider->provides() as $id) {
418
                $this->definitions[$id] = $provider;
419
            }
420
        } else {
421
            $provider->register($this);
422
        }
423
    }
424
425
    /**
426
     * Builds service provider by definition.
427
     *
428
     * @param mixed $providerDefinition class name or definition of provider.
429
     *
430
     * @throws InvalidConfigException
431
     *
432
     * @return ServiceProviderInterface instance of service provider;
433
     */
434
    private function buildProvider($providerDefinition): ServiceProviderInterface
435
    {
436
        if ($this->validate) {
437
            $this->validateDefinition($providerDefinition);
438
        }
439
        $provider = DefinitionNormalizer::normalize($providerDefinition)->resolve($this);
440
        assert($provider instanceof ServiceProviderInterface, new InvalidConfigException(
441
            sprintf(
442
                'Service provider should be an instance of %s. %s given.',
443
                ServiceProviderInterface::class,
444
                $this->getVariableType($provider)
445
            )
446
        ));
447
448
        return $provider;
449
    }
450
451
    /**
452
     * @param mixed $variable
453
     */
454
    private function getVariableType($variable): string
455
    {
456
        if (is_object($variable)) {
457
            return get_class($variable);
458
        }
459
460
        return gettype($variable);
461
    }
462
}
463