Passed
Pull Request — master (#144)
by Dmitriy
03:01
created

Container::delegateLookup()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 6
nc 3
nop 1
dl 0
loc 11
ccs 7
cts 7
cp 1
crap 3
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Di;
6
7
use Psr\Container\ContainerInterface;
8
use Yiisoft\Di\Contracts\DeferredServiceProviderInterface;
9
use Yiisoft\Di\Contracts\ServiceProviderInterface;
10
use Yiisoft\Factory\Definition\ArrayDefinition;
11
use Yiisoft\Factory\Definition\Normalizer;
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 assert;
21
use function class_exists;
22
use function get_class;
23
use function implode;
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 extends AbstractContainerConfigurator implements ContainerInterface
31
{
32
    private const TAGS_META = 'tags';
33
    private const ALLOWED_META = ['tags'];
34
35
    /**
36
     * @var array object definitions indexed by their types
37
     */
38
    private array $definitions = [];
39
    /**
40
     * @var array used to collect ids instantiated during build
41
     * to detect circular references
42
     */
43
    private array $building = [];
44
    /**
45
     * @var object[]
46
     */
47
    private array $instances = [];
48
49
    private array $tags;
50
51
    private ?CompositeContainer $rootContainer = null;
52
53
    /**
54
     * Container constructor.
55
     *
56
     * @param array $definitions Definitions to put into container.
57
     * @param ServiceProviderInterface[]|string[] $providers Service providers
58
     * to get definitions from.
59
     * @param ContainerInterface|null $rootContainer Root container to delegate
60
     * lookup to when resolving dependencies. If provided the current container
61
     * is no longer queried for dependencies.
62
     *
63
     * @throws InvalidConfigException
64
     */
65 88
    public function __construct(
66
        array $definitions = [],
67
        array $providers = [],
68
        array $tags = [],
69
        ContainerInterface $rootContainer = null
70
    ) {
71 88
        $this->tags = $tags;
72 88
        $this->delegateLookup($rootContainer);
73 88
        $this->setDefaultDefinitions();
74 88
        $this->setMultiple($definitions);
75 86
        $this->addProviders($providers);
76
77
        // Prevent circular reference to ContainerInterface
78 84
        $this->get(ContainerInterface::class);
79 84
    }
80
81 88
    private function setDefaultDefinitions(): void
82
    {
83 88
        $container = $this->rootContainer ?? $this;
84 88
        $this->setMultiple([
85 88
            ContainerInterface::class => $container,
86 88
            Injector::class => new Injector($container),
87
        ]);
88 88
    }
89
90
    /**
91
     * Returns a value indicating whether the container has the definition of the specified name.
92
     *
93
     * @param string $id class name, interface name or alias name
94
     *
95
     * @return bool whether the container is able to provide instance of class specified.
96
     *
97
     * @see set()
98
     */
99 30
    public function has($id): bool
100
    {
101 30
        if ($this->isTagAlias($id)) {
102 2
            $tag = substr($id, 4);
103 2
            return isset($this->tags[$tag]);
104
        }
105
106 28
        return isset($this->definitions[$id]) || class_exists($id);
107
    }
108
109
    /**
110
     * Returns an instance by either interface name or alias.
111
     *
112
     * Same instance of the class will be returned each time this method is called.
113
     *
114
     * @param string $id The interface or an alias name that was previously registered.
115
     *
116
     * @throws CircularReferenceException
117
     * @throws InvalidConfigException
118
     * @throws NotFoundException
119
     * @throws NotInstantiableException
120
     *
121
     * @return mixed|object An instance of the requested interface.
122
     *
123
     * @psalm-template T
124
     * @psalm-param string|class-string<T> $id
125
     * @psalm-return ($id is class-string ? T : mixed)
126
     */
127 85
    public function get($id)
128
    {
129 85
        if (!array_key_exists($id, $this->instances)) {
130 85
            $this->instances[$id] = $this->build($id);
131
        }
132
133 85
        return $this->instances[$id];
134
    }
135
136
    /**
137
     * Delegate service lookup to another container.
138
     *
139
     * @param ContainerInterface $container
140
     */
141 88
    protected function delegateLookup(?ContainerInterface $container): void
142
    {
143 88
        if ($container === null) {
144 88
            return;
145
        }
146 8
        if ($this->rootContainer === null) {
147 8
            $this->rootContainer = new CompositeContainer();
148 8
            $this->setDefaultDefinitions();
149
        }
150
151 8
        $this->rootContainer->attach($container);
0 ignored issues
show
Bug introduced by
The method attach() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

151
        $this->rootContainer->/** @scrutinizer ignore-call */ 
152
                              attach($container);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
152 8
    }
153
154
    /**
155
     * Sets a definition to the container. Definition may be defined multiple ways.
156
     *
157
     * @param string $id
158
     * @param mixed $definition
159
     *
160
     * @throws InvalidConfigException
161
     *
162
     * @see `Normalizer::normalize()`
163
     */
164 88
    protected function set(string $id, $definition): void
165
    {
166 88
        [$definition, $meta] = Normalizer::parse($definition, self::ALLOWED_META);
167
168 88
        Normalizer::validate($definition);
169 88
        if (isset($meta[self::TAGS_META])) {
170 8
            $this->validateTags($meta[self::TAGS_META]);
171 8
            $this->setTags($id,$meta[self::TAGS_META]);
172
        }
173
174 88
        unset($this->instances[$id]);
175 88
        $this->definitions[$id] = $definition;
176 88
    }
177
178
    /**
179
     * Sets multiple definitions at once.
180
     *
181
     * @param array $config definitions indexed by their ids
182
     *
183
     * @throws InvalidConfigException
184
     */
185 88
    protected function setMultiple(array $config): void
186
    {
187 88
        foreach ($config as $id => $definition) {
188 88
            if (!is_string($id)) {
189 1
                throw new InvalidConfigException(sprintf('Key must be a string. %s given.', $this->getVariableType($id)));
190
            }
191 88
            $this->set($id, $definition);
192
        }
193 88
    }
194
195 8
    private function validateTags(array $tags): void
196
    {
197 8
        foreach ($tags as $tag) {
198 8
            if (!(is_string($tag))) {
199
                throw new InvalidConfigException('Invalid tag: ' . var_export($tag, true));
200
            }
201
        }
202 8
    }
203
204 8
    private function setTags(string $id, array $tags): void
205
    {
206 8
        foreach ($tags as $tag) {
207 8
            if (!isset($this->tags[$tag]) || !in_array($id, $this->tags[$tag])) {
208 8
                $this->tags[$tag][] = $id;
209
            }
210
        }
211 8
    }
212
213
    /**
214
     * Creates new instance by either interface name or alias.
215
     *
216
     * @param string $id The interface or an alias name that was previously registered.
217
     *
218
     * @throws CircularReferenceException
219
     * @throws InvalidConfigException
220
     * @throws NotFoundException
221
     *
222
     * @return mixed|object New built instance of the specified class.
223
     *
224
     * @internal
225
     */
226 85
    private function build(string $id)
227
    {
228 85
        if ($this->isTagAlias($id)) {
229 9
            return $this->getTaggedServices($id);
230
        }
231
232 85
        if (isset($this->building[$id])) {
233 9
            if ($id === ContainerInterface::class) {
234 2
                return $this;
235
            }
236 7
            throw new CircularReferenceException(sprintf(
237 7
                'Circular reference to "%s" detected while building: %s.',
238
                $id,
239 7
                implode(',', array_keys($this->building))
240
            ));
241
        }
242
243 85
        $this->building[$id] = 1;
244
        try {
245 85
            $object = $this->buildInternal($id);
246 85
        } finally {
247 85
            unset($this->building[$id]);
248
        }
249
250 85
        return $object;
251
    }
252
253 85
    private function isTagAlias(string $id): bool
254
    {
255 85
        return strpos($id, 'tag@') === 0;
256
    }
257
258 9
    private function getTaggedServices(string $tagAlias): array
259
    {
260 9
        $tag = substr($tagAlias, 4);
261 9
        $services = [];
262 9
        if (isset($this->tags[$tag])) {
263 8
            foreach ($this->tags[$tag] as $service) {
264 8
                $services[] = $this->get($service);
265
            }
266
        }
267
268 9
        return $services;
269
    }
270
271
    /**
272
     * @param mixed $definition
273
     */
274 85
    private function processDefinition($definition): void
275
    {
276 85
        if ($definition instanceof DeferredServiceProviderInterface) {
277 1
            $definition->register($this);
278
        }
279 85
    }
280
281
    /**
282
     * @param string $id
283
     *
284
     * @throws InvalidConfigException
285
     * @throws NotFoundException
286
     *
287
     * @return mixed|object
288
     */
289 85
    private function buildInternal(string $id)
290
    {
291 85
        if (!isset($this->definitions[$id])) {
292 51
            return $this->buildPrimitive($id);
293
        }
294 85
        $this->processDefinition($this->definitions[$id]);
295 85
        $definition = Normalizer::normalize($this->definitions[$id], $id, [], self::ALLOWED_META);
296
297 85
        return $definition->resolve($this->rootContainer ?? $this);
298
    }
299
300
    /**
301
     * @param string $class
302
     *
303
     * @throws InvalidConfigException
304
     * @throws NotFoundException
305
     *
306
     * @return mixed|object
307
     */
308 51
    private function buildPrimitive(string $class)
309
    {
310 51
        if (class_exists($class)) {
311 49
            $definition = new ArrayDefinition([ArrayDefinition::CLASS_NAME => $class]);
312
313 49
            return $definition->resolve($this->rootContainer ?? $this);
314
        }
315
316 4
        throw new NotFoundException($class);
317
    }
318
319 86
    private function addProviders(array $providers): void
320
    {
321 86
        foreach ($providers as $provider) {
322 6
            $this->addProvider($provider);
323
        }
324 84
    }
325
326
    /**
327
     * Adds service provider to the container. Unless service provider is deferred
328
     * it would be immediately registered.
329
     *
330
     * @param mixed $providerDefinition
331
     *
332
     * @throws InvalidConfigException
333
     * @throws NotInstantiableException
334
     *
335
     * @see ServiceProviderInterface
336
     * @see DeferredServiceProviderInterface
337
     */
338 6
    private function addProvider($providerDefinition): void
339
    {
340 6
        $provider = $this->buildProvider($providerDefinition);
341
342 5
        if ($provider instanceof DeferredServiceProviderInterface) {
343 1
            foreach ($provider->provides() as $id) {
344 1
                $this->definitions[$id] = $provider;
345
            }
346
        } else {
347 4
            $provider->register($this);
348
        }
349 4
    }
350
351
    /**
352
     * Builds service provider by definition.
353
     *
354
     * @param mixed $providerDefinition class name or definition of provider.
355
     *
356
     * @throws InvalidConfigException
357
     *
358
     * @return ServiceProviderInterface instance of service provider;
359
     */
360 6
    private function buildProvider($providerDefinition): ServiceProviderInterface
361
    {
362 6
        $provider = Normalizer::normalize($providerDefinition)->resolve($this);
363 5
        assert($provider instanceof ServiceProviderInterface, new InvalidConfigException(
364 5
            sprintf(
365 5
                'Service provider should be an instance of %s. %s given.',
366 5
                ServiceProviderInterface::class,
367 5
                $this->getVariableType($provider)
368
            )
369
        ));
370
371 5
        return $provider;
372
    }
373
374
    /**
375
     * @param mixed $variable
376
     */
377 6
    private function getVariableType($variable): string
378
    {
379 6
        if (is_object($variable)) {
380 5
            return get_class($variable);
381
        }
382
383 1
        return gettype($variable);
384
    }
385
}
386