Test Failed
Pull Request — master (#212)
by Sergei
10:45 queued 07:10
created

Container::getVariableType()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 7
ccs 0
cts 0
cp 0
crap 6
rs 10
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 96
     * @param ServiceProviderInterface[]|string[] $providers Service providers
70
     * to get definitions from.
71
     * @param ContainerInterface|null $rootContainer Root container to delegate
72
     * lookup to when resolving dependencies. If provided the current container
73
     * is no longer queried for dependencies.
74
     *
75 96
     * @throws InvalidConfigException
76 96
     */
77 96
    public function __construct(
78 96
        array $definitions = [],
79 93
        array $providers = [],
80
        array $tags = [],
81
        ContainerInterface $rootContainer = null,
82 91
        bool $validate = true
83 91
    ) {
84
        $this->tags = $tags;
85
        $this->validate = $validate;
86
        $this->delegateLookup($rootContainer);
87
        $this->setDefaultDefinitions();
88
        $this->setMultiple($definitions);
89
        $this->addProviders($providers);
90
91
        // Prevent circular reference to ContainerInterface
92
        $this->get(ContainerInterface::class);
93
    }
94 32
95
    /**
96 32
     * Returns a value indicating whether the container has the definition of the specified name.
97 2
     *
98 2
     * @param string $id class name, interface name or alias name
99
     *
100
     * @return bool whether the container is able to provide instance of class specified.
101 30
     *
102
     * @see set()
103
     */
104
    public function has($id): bool
105
    {
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 92
     * @throws InvalidConfigException
123
     * @throws NotFoundException
124 92
     * @throws NotInstantiableException
125 4
     *
126 4
     * @return mixed|object An instance of the requested interface.
127 4
     *
128 4
     * @psalm-template T
129
     * @psalm-param string|class-string<T> $id
130
     * @psalm-return ($id is class-string ? T : mixed)
131 4
     */
132
    public function get($id)
133
    {
134 92
        if ($id === StateResetter::class && !isset($this->definitions[$id])) {
135 92
            $resetters = [];
136
            foreach ($this->resetters as $serviceId => $callback) {
137
                if (isset($this->instances[$serviceId])) {
138 92
                    $resetters[] = $callback->bindTo($this->instances[$serviceId], get_class($this->instances[$serviceId]));
139
                }
140
            }
141
            return new StateResetter($resetters, $this);
142
        }
143
144
        if (!array_key_exists($id, $this->instances)) {
145
            $this->instances[$id] = $this->build($id);
146 96
        }
147
148 96
        return $this->instances[$id];
149 96
    }
150
151 8
    /**
152 8
     * Delegate service lookup to another container.
153 8
     *
154
     * @param ContainerInterface $container
155
     */
156 8
    protected function delegateLookup(?ContainerInterface $container): void
157 8
    {
158
        if ($container === null) {
159
            return;
160
        }
161
        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 96
    /**
170
     * Sets a definition to the container. Definition may be defined multiple ways.
171 96
     *
172
     * @param string $id
173 96
     * @param mixed $definition
174 96
     *
175 8
     * @throws InvalidConfigException
176 8
     *
177
     * @see `DefinitionNormalizer::normalize()`
178 96
     */
179 5
    protected function set(string $id, $definition): void
180
    {
181
        [$definition, $meta] = DefinitionParser::parse($definition);
182 96
        if ($this->validate) {
183 96
            $this->validateDefinition($definition, $id);
184 96
            $this->validateMeta($meta);
185
        }
186
187
        if (isset($meta[self::META_TAGS])) {
188
            if ($this->validate) {
189
                $this->validateTags($meta[self::META_TAGS]);
190
            }
191
            $this->setTags($id, $meta[self::META_TAGS]);
192
        }
193 96
        if (isset($meta[self::META_RESET])) {
194
            $this->setResetter($id, $meta[self::META_RESET]);
195 96
        }
196 96
197 1
        unset($this->instances[$id]);
198
        $this->definitions[$id] = $definition;
199 96
    }
200
201 96
    /**
202
     * Sets multiple definitions at once.
203 96
     *
204
     * @param array $config definitions indexed by their ids
205 96
     *
206 96
     * @throws InvalidConfigException
207 96
     */
208 96
    protected function setMultiple(array $config): void
209
    {
210 96
        foreach ($config as $id => $definition) {
211
            if ($this->validate && !is_string($id)) {
212 8
                throw new InvalidConfigException(sprintf('Key must be a string. %s given.', $this->getVariableType($id)));
213
            }
214 8
            $this->set($id, $definition);
215 8
        }
216
    }
217
218
    private function setDefaultDefinitions(): void
219 8
    {
220
        $container = $this->rootContainer ?? $this;
221 8
        $this->setMultiple([
222
            ContainerInterface::class => $container,
223 8
            Injector::class => new Injector($container),
224 8
        ]);
225 8
    }
226
227
    /**
228 8
     * @param mixed $definition
229
     *
230 4
     * @throws InvalidConfigException
231
     */
232 4
    private function validateDefinition($definition, ?string $id = null): void
233 4
    {
234
        if (is_array($definition) && isset($definition[DefinitionParser::IS_PREPARED_ARRAY_DEFINITION_DATA])) {
235
            [$class, $constructorArguments, $methodsAndProperties] = $definition;
236
            $definition = array_merge(
237
                $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 92
    private function validateMeta(array $meta): void
249
    {
250 92
        foreach ($meta as $key => $_value) {
251 9
            if (!in_array($key, self::ALLOWED_META, true)) {
252
                throw new InvalidConfigException(
253
                    sprintf(
254 92
                        'Invalid definition: metadata "%s" is not allowed. Did you mean "%s()" or "$%s"?',
255 9
                        $key,
256 2
                        $key,
257
                        $key,
258 7
                    )
259 7
                );
260
            }
261 7
        }
262
    }
263
264
    private function validateTags(array $tags): void
265 92
    {
266
        foreach ($tags as $tag) {
267 92
            if (!is_string($tag)) {
268 92
                throw new InvalidConfigException('Invalid tag. Expected a string, got ' . var_export($tag, true) . '.');
269 92
            }
270
        }
271
    }
272 92
273
    private function setTags(string $id, array $tags): void
274
    {
275 92
        foreach ($tags as $tag) {
276
            if (!isset($this->tags[$tag]) || !in_array($id, $this->tags[$tag], true)) {
277 92
                $this->tags[$tag][] = $id;
278
            }
279
        }
280 9
    }
281
282 9
    private function setResetter(string $id, Closure $resetter): void
283 9
    {
284 9
        $this->resetters[$id] = $resetter;
285 8
    }
286 8
287
    /**
288
     * Creates new instance by either interface name or alias.
289
     *
290 9
     * @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 92
     * @return mixed|object New built instance of the specified class.
297
     *
298 92
     * @internal
299 1
     */
300
    private function build(string $id)
301 92
    {
302
        if ($this->isTagAlias($id)) {
303
            return $this->getTaggedServices($id);
304
        }
305
306
        if (isset($this->building[$id])) {
307
            if ($id === ContainerInterface::class) {
308
                return $this;
309
            }
310
            throw new CircularReferenceException(sprintf(
311 92
                'Circular reference to "%s" detected while building: %s.',
312
                $id,
313 92
                implode(',', array_keys($this->building))
314 51
            ));
315
        }
316 92
317 92
        $this->building[$id] = 1;
318
        try {
319 92
            $object = $this->buildInternal($id);
320
        } finally {
321
            unset($this->building[$id]);
322
        }
323
324
        return $object;
325
    }
326
327
    private function isTagAlias(string $id): bool
328
    {
329
        return strpos($id, 'tag@') === 0;
330 51
    }
331
332 51
    private function getTaggedServices(string $tagAlias): array
333 49
    {
334
        $tag = substr($tagAlias, 4);
335 49
        $services = [];
336
        if (isset($this->tags[$tag])) {
337
            foreach ($this->tags[$tag] as $service) {
338 4
                $services[] = $this->get($service);
339
            }
340
        }
341 93
342
        return $services;
343 93
    }
344 6
345
    /**
346 91
     * @param mixed $definition
347
     */
348
    private function processDefinition($definition): void
349
    {
350
        if ($definition instanceof DeferredServiceProviderInterface) {
351
            $definition->register($this);
352
        }
353
    }
354
355
    /**
356
     * @param string $id
357
     *
358
     * @throws InvalidConfigException
359
     * @throws NotFoundException
360 6
     *
361
     * @return mixed|object
362 6
     */
363
    private function buildInternal(string $id)
364 5
    {
365 1
        if (!isset($this->definitions[$id])) {
366 1
            return $this->buildPrimitive($id);
367
        }
368
        $this->processDefinition($this->definitions[$id]);
369 4
        $definition = DefinitionNormalizer::normalize($this->definitions[$id], $id);
370
371 4
        return $definition->resolve($this->rootContainer ?? $this);
372
    }
373
374
    /**
375
     * @param string $class
376
     *
377
     * @throws InvalidConfigException
378
     * @throws NotFoundException
379
     *
380
     * @return mixed|object
381
     */
382 6
    private function buildPrimitive(string $class)
383
    {
384 6
        if (class_exists($class)) {
385 5
            $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 5
387 5
            return $definition->resolve($this->rootContainer ?? $this);
388 5
        }
389 5
390
        throw new NotFoundException($class);
391
    }
392
393 5
    private function addProviders(array $providers): void
394
    {
395
        foreach ($providers as $provider) {
396
            $this->addProvider($provider);
397
        }
398
    }
399 6
400
    /**
401 6
     * Adds service provider to the container. Unless service provider is deferred
402 5
     * it would be immediately registered.
403
     *
404
     * @param mixed $providerDefinition
405 1
     *
406
     * @throws InvalidConfigException
407
     * @throws NotInstantiableException
408
     *
409
     * @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