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