Passed
Pull Request — master (#241)
by Dmitriy
02:20
created

Container::build()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 4

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 4
eloc 15
nc 5
nop 1
dl 0
loc 25
ccs 14
cts 14
cp 1
crap 4
rs 9.7666
c 2
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
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 = $definition['class'];
206 39
            $constructorArguments = $definition['__construct()'];
207 39
            $methodsAndProperties = $definition['methodsAndProperties'];
208 39
            $definition = array_merge(
209 39
                $class === null ? [] : [ArrayDefinition::CLASS_NAME => $class],
210 39
                [ArrayDefinition::CONSTRUCTOR => $constructorArguments],
211
                $methodsAndProperties,
212
            );
213
        }
214
215 95
        if ($definition instanceof ExtensibleService) {
216
            throw new InvalidConfigException('Invalid definition. ExtensibleService is only allowed in provider extensions.');
217
        }
218
219 95
        DefinitionValidator::validate($definition, $id);
220 95
    }
221
222
    /**
223
     * @throws InvalidConfigException
224
     */
225 95
    private function validateMeta(array $meta): void
226
    {
227 95
        foreach ($meta as $key => $_value) {
228 16
            if (!in_array($key, self::ALLOWED_META, true)) {
229 3
                throw new InvalidConfigException(
230 3
                    sprintf(
231 3
                        'Invalid definition: metadata "%s" is not allowed. Did you mean "%s()" or "$%s"?',
232
                        $key,
233
                        $key,
234
                        $key,
235
                    )
236
                );
237
            }
238
        }
239 95
    }
240
241 8
    private function validateTags(array $tags): void
242
    {
243 8
        foreach ($tags as $tag) {
244 8
            if (!is_string($tag)) {
245
                throw new InvalidConfigException('Invalid tag. Expected a string, got ' . var_export($tag, true) . '.');
246
            }
247
        }
248 8
    }
249
250 8
    private function setTags(string $id, array $tags): void
251
    {
252 8
        foreach ($tags as $tag) {
253 8
            if (!isset($this->tags[$tag]) || !in_array($id, $this->tags[$tag], true)) {
254 8
                $this->tags[$tag][] = $id;
255
            }
256
        }
257 8
    }
258
259 4
    private function setResetter(string $id, Closure $resetter): void
260
    {
261 4
        $this->resetters[$id] = $resetter;
262 4
    }
263
264
    /**
265
     * Creates new instance by either interface name or alias.
266
     *
267
     * @param string $id The interface or an alias name that was previously registered.
268
     *
269
     * @throws CircularReferenceException
270
     * @throws InvalidConfigException
271
     * @throws NotFoundException
272
     *
273
     * @return mixed|object New built instance of the specified class.
274
     *
275
     * @internal
276
     */
277 84
    private function build(string $id)
278
    {
279 84
        if ($this->isTagAlias($id)) {
280 9
            return $this->getTaggedServices($id);
281
        }
282
283 83
        if (isset($this->building[$id])) {
284 81
            if ($id === ContainerInterface::class) {
285 81
                return $this;
286
            }
287 7
            throw new CircularReferenceException(sprintf(
288 7
                'Circular reference to "%s" detected while building: %s.',
289
                $id,
290 7
                implode(',', array_keys($this->building))
291
            ));
292
        }
293
294 83
        $this->building[$id] = 1;
295
        try {
296 83
            $object = $this->buildInternal($id);
297 81
        } finally {
298 83
            unset($this->building[$id]);
299
        }
300
301 81
        return $object;
302
    }
303
304 88
    private function isTagAlias(string $id): bool
305
    {
306 88
        return strpos($id, 'tag@') === 0;
307
    }
308
309 9
    private function getTaggedServices(string $tagAlias): array
310
    {
311 9
        $tag = substr($tagAlias, 4);
312 9
        $services = [];
313 9
        if (isset($this->tags[$tag])) {
314 8
            foreach ($this->tags[$tag] as $service) {
315 8
                $services[] = $this->get($service);
316
            }
317
        }
318
319 9
        return $services;
320
    }
321
322
    /**
323
     * @param string $id
324
     *
325
     * @throws InvalidConfigException
326
     * @throws NotFoundException
327
     *
328
     * @return mixed|object
329
     */
330 83
    private function buildInternal(string $id)
331
    {
332 83
        if (!isset($this->definitions[$id])) {
333 50
            return $this->buildPrimitive($id);
334
        }
335 81
        $definition = DefinitionNormalizer::normalize($this->definitions[$id], $id);
336
        /** @psalm-suppress RedundantPropertyInitializationCheck */
337 81
        $this->dependencyResolver ??= new DependencyResolver($this->get(ContainerInterface::class));
338
339 81
        return $definition->resolve($this->dependencyResolver);
340
    }
341
342
    /**
343
     * @param string $class
344
     *
345
     * @throws InvalidConfigException
346
     * @throws NotFoundException
347
     *
348
     * @return mixed|object
349
     */
350 50
    private function buildPrimitive(string $class)
351
    {
352 50
        if (class_exists($class)) {
353 48
            $definition = ArrayDefinition::fromPreparedData($class);
354
            /** @psalm-suppress RedundantPropertyInitializationCheck */
355 48
            $this->dependencyResolver ??= new DependencyResolver($this->get(ContainerInterface::class));
356
357 48
            return $definition->resolve($this->dependencyResolver);
358
        }
359
360 5
        throw new NotFoundException($class);
361
    }
362
363 89
    private function addProviders(array $providers): void
364
    {
365 89
        $extensions = [];
366 89
        foreach ($providers as $provider) {
367 5
            $providerInstance = $this->buildProvider($provider);
368 5
            $extensions[] = $providerInstance->getExtensions();
369 5
            $this->addProviderDefinitions($providerInstance);
370
        }
371
372 89
        foreach ($extensions as $providerExtensions) {
373 5
            foreach ($providerExtensions as $id => $extension) {
374 4
                if (!isset($this->definitions[$id])) {
375 1
                    throw new InvalidConfigException("Extended service \"$id\" doesn't exist.");
376
                }
377
378 3
                if (!$this->definitions[$id] instanceof ExtensibleService) {
379 3
                    $this->definitions[$id] = new ExtensibleService($this->definitions[$id]);
380
                }
381
382 3
                $this->definitions[$id]->addExtension($extension);
383
            }
384
        }
385 88
    }
386
387
    /**
388
     * Adds service provider definitions to the container.
389
     *
390
     * @param object $provider
391
     *
392
     * @throws InvalidConfigException
393
     * @throws NotInstantiableException
394
     *
395
     * @see ServiceProviderInterface
396
     */
397 5
    private function addProviderDefinitions($provider): void
398
    {
399 5
        $definitions = $provider->getDefinitions();
400 5
        $this->setMultiple($definitions);
401 5
    }
402
403
    /**
404
     * Builds service provider by definition.
405
     *
406
     * @param mixed $provider Class name or instance of provider.
407
     *
408
     * @throws InvalidConfigException If provider argument is not valid.
409
     *
410
     * @return ServiceProviderInterface Instance of service provider.
411
     *
412
     * @psalm-suppress MoreSpecificReturnType
413
     */
414 5
    private function buildProvider($provider): ServiceProviderInterface
415
    {
416 5
        if ($this->validate && !(is_string($provider) || is_object($provider) && $provider instanceof ServiceProviderInterface)) {
417
            throw new InvalidConfigException(
418
                sprintf(
419
                    'Service provider should be a class name or an instance of %s. %s given.',
420
                    ServiceProviderInterface::class,
421
                    $this->getVariableType($provider)
422
                )
423
            );
424
        }
425
426 5
        $providerInstance = is_object($provider) ? $provider : new $provider();
427 5
        if (!$providerInstance instanceof ServiceProviderInterface) {
428
            throw new InvalidConfigException(
429
                sprintf(
430
                    'Service provider should be an instance of %s. %s given.',
431
                    ServiceProviderInterface::class,
432
                    $this->getVariableType($providerInstance)
433
                )
434
            );
435
        }
436
437
        /**
438
         * @psalm-suppress LessSpecificReturnStatement
439
         */
440 5
        return $providerInstance;
441
    }
442
443
    /**
444
     * @param mixed $variable
445
     */
446 1
    private function getVariableType($variable): string
447
    {
448 1
        if (is_object($variable)) {
449
            return get_class($variable);
450
        }
451
452 1
        return gettype($variable);
453
    }
454
}
455