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

Container::setDefaultDefinitions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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