Test Failed
Pull Request — master (#233)
by Alexander
02:26
created

Container::addProviderDefinitions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

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

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

419
            throw /** @scrutinizer ignore-call */ InvalidConfigException(
Loading history...
420 1
                sprintf(
421
                    'Service provider should be a class name or an instance of %s. %s given.',
422
                    ServiceProviderInterface::class,
423 4
                    $this->getVariableType($provider)
424
                )
425 4
            );
426
        }
427
428
        $providerInstance = is_object($provider) ? $provider : new $provider();
429
        if (!$providerInstance instanceof ServiceProviderInterface) {
430
            throw InvalidConfigException(
431
                sprintf(
432
                    'Service provider should be an instance of %s. %s given.',
433
                    ServiceProviderInterface::class,
434
                    $this->getVariableType($providerInstance)
435
                )
436 6
            );
437
        }
438 6
439 6
        /**
440
         * @psalm-suppress LessSpecificReturnStatement
441 5
         */
442 5
        return $providerInstance;
443 5
    }
444 5
445 5
    /**
446 5
     * @param mixed $variable
447
     */
448
    private function getVariableType($variable): string
449
    {
450 5
        if (is_object($variable)) {
451
            return get_class($variable);
452
        }
453
454
        return gettype($variable);
455
    }
456
}
457