Passed
Push — master ( ee03c1...dad2d2 )
by Alexander
02:31
created

Container::buildProvider()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 21.5206

Importance

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