Passed
Push — upgrade-psr ( 9a5b54...3d23e3 )
by Dmitriy
07:19 queued 05:03
created

Container::validateDefinition()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5.0187

Importance

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