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