Passed
Pull Request — master (#240)
by Dmitriy
02:51
created

Container::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

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