Passed
Pull Request — master (#233)
by Dmitriy
02:25
created

Container::validateDefinition()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5.0342

Importance

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