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

Container::addProvider()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 3
nop 2
dl 0
loc 10
ccs 6
cts 6
cp 1
crap 3
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;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Di\Contracts\Def...erviceProviderInterface 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...
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 class_exists;
22
use function get_class;
23
use function implode;
24
use function in_array;
25
use function is_array;
26
use function is_object;
27
use function is_string;
28
29
/**
30
 * Container implements a [dependency injection](http://en.wikipedia.org/wiki/Dependency_injection) container.
31
 */
32
final class Container implements ContainerInterface
33
{
34
    private const META_TAGS = 'tags';
35
    private const META_RESET = 'reset';
36
    private const ALLOWED_META = [self::META_TAGS, self::META_RESET];
37
38
    /**
39
     * @var array object definitions indexed by their types
40
     */
41
    private array $definitions = [];
42
    /**
43
     * @var array used to collect ids instantiated during build
44
     * to detect circular references
45
     */
46
    private array $building = [];
47
48
    /**
49
     * @var bool $validate Validate definitions when set
50
     */
51
    private bool $validate;
52
53
    /**
54
     * @var object[]
55
     */
56
    private array $instances = [];
57
58
    private array $tags;
59
60
    private array $resetters = [];
61
    /** @psalm-suppress PropertyNotSetInConstructor */
62
    private DependencyResolver $dependencyResolver;
63
64
    /**
65
     * Container constructor.
66
     *
67
     * @param array $definitions Definitions to put into container.
68
     * @param array $providers Service providers to get definitions from.
69
     * lookup to when resolving dependencies. If provided the current container
70
     * is no longer queried for dependencies.
71
     *
72
     * @throws InvalidConfigException
73
     *
74
     * @psalm-suppress PropertyNotSetInConstructor
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 22
    public function has($id): bool
99
    {
100 22
        if ($this->isTagAlias($id)) {
101 2
            $tag = substr($id, 4);
102 2
            return isset($this->tags[$tag]);
103
        }
104
105 20
        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 35
            [$class, $constructorArguments, $methodsAndProperties] = $definition;
211 35
            $definition = array_merge(
212 35
                $class === null ? [] : [ArrayDefinition::CLASS_NAME => $class],
213 35
                [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 string $id
327
     *
328
     * @throws InvalidConfigException
329
     * @throws NotFoundException
330
     *
331
     * @return mixed|object
332
     */
333 77
    private function buildInternal(string $id)
334
    {
335 77
        if (!isset($this->definitions[$id])) {
336 44
            return $this->buildPrimitive($id);
337
        }
338 75
        $definition = DefinitionNormalizer::normalize($this->definitions[$id], $id);
339
        /** @psalm-suppress RedundantPropertyInitializationCheck */
340 75
        $this->dependencyResolver = $this->dependencyResolver ?? new DependencyResolver($this->get(ContainerInterface::class));
341
342 75
        return $definition->resolve($this->dependencyResolver);
343
    }
344
345
    /**
346
     * @param string $class
347
     *
348
     * @throws InvalidConfigException
349
     * @throws NotFoundException
350
     *
351
     * @return mixed|object
352
     */
353 44
    private function buildPrimitive(string $class)
354
    {
355 44
        if (class_exists($class)) {
356 42
            $definition = ArrayDefinition::fromPreparedData($class);
357
            /** @psalm-suppress RedundantPropertyInitializationCheck */
358 42
            $this->dependencyResolver = $this->dependencyResolver ?? new DependencyResolver($this->get(ContainerInterface::class));
359
360 42
            return $definition->resolve($this->dependencyResolver);
361
        }
362
363 3
        throw new NotFoundException($class);
364
    }
365
366 82
    private function addProviders(array $providers): void
367
    {
368 82
        $extensions = [];
369 82
        foreach ($providers as $provider) {
370 3
            $providerInstance = $this->buildProvider($provider);
371 3
            $extensions[] = $providerInstance->getExtensions();
372 3
            $this->addProviderDefinitions($providerInstance);
373
        }
374
375 82
        foreach ($extensions as $providerExtensions) {
376 3
            foreach ($providerExtensions as $id => $extension) {
377 2
                if (!isset($this->definitions[$id])) {
378
                    throw new InvalidConfigException("Extended service \"$id\" doesn't exist.");
379
                }
380
381 2
                if (!$this->definitions[$id] instanceof ExtensibleService) {
382 2
                    $this->definitions[$id] = new ExtensibleService($this->definitions[$id]);
383
                }
384
385 2
                $this->definitions[$id]->addExtension($extension);
386
            }
387
        }
388 82
    }
389
390
    /**
391
     * Adds service provider definitions to the container.
392
     *
393
     * @param object $provider
394
     *
395
     * @throws InvalidConfigException
396
     * @throws NotInstantiableException
397
     *
398
     * @see ServiceProviderInterface
399
     */
400 3
    private function addProviderDefinitions($provider): void
401
    {
402 3
        $definitions = $provider->getDefinitions();
403 3
        $this->setMultiple($definitions);
404 3
    }
405
406
    /**
407
     * Builds service provider by definition.
408
     *
409
     * @param mixed $provider class name or instance of provider.
410
     *
411
     * @throws InvalidConfigException
412
     *
413
     * @return ServiceProviderInterface instance of service provider;
414
     *
415
     * @psalm-suppress MoreSpecificReturnType
416
     */
417 3
    private function buildProvider($provider): ServiceProviderInterface
418
    {
419 3
        if ($this->validate) {
420 3
            if (!is_string($provider)) {
421 2
                new InvalidConfigException(
422 2
                    sprintf(
423 2
                        'Service provider should be a class name or an instance of %s. %s given.',
424 2
                        ServiceProviderInterface::class,
425 2
                        $this->getVariableType($provider)
426
                    )
427
                );
428
            }
429
        }
430
431 3
        $providerInstance = is_object($provider) ? $provider : new $provider();
432 3
        if (!$providerInstance instanceof ServiceProviderInterface) {
433
            new InvalidConfigException(
434
                sprintf(
435
                    'Service provider should be an instance of %s. %s given.',
436
                    ServiceProviderInterface::class,
437
                    $this->getVariableType($providerInstance)
438
                )
439
            );
440
        }
441
442
        /**
443
         * @psalm-suppress LessSpecificReturnStatement
444
         */
445 3
        return $providerInstance;
446
    }
447
448
    /**
449
     * @param mixed $variable
450
     */
451 3
    private function getVariableType($variable): string
452
    {
453 3
        if (is_object($variable)) {
454 2
            return get_class($variable);
455
        }
456
457 1
        return gettype($variable);
458
    }
459
}
460