Test Failed
Push — rename ( 0b3dce )
by Sergei
03:01
created

Container::buildProvider()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

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