Passed
Pull Request — master (#144)
by Dmitriy
33:48 queued 18:43
created

Container::processDefinition()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 1
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 2
rs 10
c 0
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\Definitions\DynamicReference;
11
use Yiisoft\Factory\Definitions\Reference;
12
use Yiisoft\Factory\Exceptions\CircularReferenceException;
13
use Yiisoft\Factory\Exceptions\InvalidConfigException;
14
use Yiisoft\Factory\Exceptions\NotFoundException;
15
use Yiisoft\Factory\Exceptions\NotInstantiableException;
16
use Yiisoft\Factory\Definitions\Normalizer;
17
use Yiisoft\Factory\Definitions\ArrayDefinition;
18
19
/**
20
 * Container implements a [dependency injection](http://en.wikipedia.org/wiki/Dependency_injection) container.
21
 */
22
final class Container extends AbstractContainerConfigurator implements ContainerInterface
23
{
24
    /**
25
     * @var array object definitions indexed by their types
26
     */
27
    private array $definitions = [];
28
    /**
29
     * @var array used to collect ids instantiated during build
30
     * to detect circular references
31
     */
32
    private array $building = [];
33
34
    /**
35
     * @var object[]
36
     */
37
    private array $instances = [];
38
39
    private array $tags;
40
41
    private ?ContainerInterface $rootContainer = null;
42
43
    /**
44
     * Container constructor.
45
     *
46
     * @param array $definitions Definitions to put into container.
47
     * @param ServiceProviderInterface[]|string[] $providers Service providers to get definitions from.
48
     *
49
     * @param ContainerInterface|null $rootContainer Root container to delegate lookup to in case definition
50
     * is not found in current container.
51 56
     * @throws InvalidConfigException
52
     */
53
    public function __construct(
54
        array $definitions = [],
55
        array $providers = [],
56 56
        array $tags = [],
57 55
        ContainerInterface $rootContainer = null
58 54
    ) {
59 5
        $this->tags = $tags;
60
        $this->setMultiple($definitions);
61 54
        $this->addProviders($providers);
62
        if ($rootContainer !== null) {
63
            $this->delegateLookup($rootContainer);
64
        }
65
    }
66
67
    /**
68
     * Returns a value indicating whether the container has the definition of the specified name.
69 24
     * @param string $id class name, interface name or alias name
70
     * @return bool whether the container is able to provide instance of class specified.
71 24
     * @see set()
72
     */
73
    public function has($id): bool
74
    {
75
        return isset($this->definitions[$id]) || class_exists($id);
76
    }
77
78
    /**
79
     * Returns an instance by either interface name or alias.
80
     *
81
     * Same instance of the class will be returned each time this method is called.
82
     *
83
     * @param string|Reference $id The interface or an alias name that was previously registered.
84
     * @return object An instance of the requested interface.
85
     * @throws CircularReferenceException
86 50
     * @throws InvalidConfigException
87
     * @throws NotFoundException
88 50
     * @throws NotInstantiableException
89 50
     */
90
    public function get($id)
91
    {
92 41
        if (!isset($this->instances[$id])) {
93
            $this->instances[$id] = $this->build($id);
0 ignored issues
show
Bug introduced by
It seems like $id can also be of type Yiisoft\Factory\Definitions\Reference; however, parameter $id of Yiisoft\Di\Container::build() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

93
            $this->instances[$id] = $this->build(/** @scrutinizer ignore-type */ $id);
Loading history...
94
        }
95
96
        return $this->instances[$id];
97
    }
98
99 5
    /**
100
     * Delegate service lookup to another container.
101 5
     * @param ContainerInterface $container
102 5
     */
103
    protected function delegateLookup(ContainerInterface $container): void
104
    {
105 5
        if ($this->rootContainer === null) {
106 5
            $this->rootContainer = new CompositeContainer();
107
        }
108
109
        $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

109
        $this->rootContainer->/** @scrutinizer ignore-call */ 
110
                              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...
Bug introduced by
The method attach() does not exist on Psr\Container\ContainerInterface. It seems like you code against a sub-type of Psr\Container\ContainerInterface such as Yiisoft\Di\CompositeContainer or Yiisoft\Di\CompositeContextContainer. ( Ignorable by Annotation )

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

109
        $this->rootContainer->/** @scrutinizer ignore-call */ 
110
                              attach($container);
Loading history...
110
    }
111
112
    /**
113
     * Sets a definition to the container. Definition may be defined multiple ways.
114
     * @param string $id
115 48
     * @param mixed $definition
116
     * @throws InvalidConfigException
117 48
     * @see `Normalizer::normalize()`
118 47
     */
119 47
    protected function set(string $id, $definition): void
120 47
    {
121
        $tags = $this->extractTags($definition);
122
        $definition = $this->extractDefinition($definition);
123
        $this->validateDefinition($definition);
124
        $this->setTags($id, $tags);
125
        $this->instances[$id] = null;
126
        $this->definitions[$id] = $definition;
127 56
    }
128
129 56
    /**
130 45
     * Sets multiple definitions at once.
131
     * @param array $config definitions indexed by their ids
132 55
     * @throws InvalidConfigException
133
     */
134
    protected function setMultiple(array $config): void
135
    {
136
        foreach ($config as $id => $definition) {
137
            $this->set((string)$id, $definition);
138
        }
139
    }
140
141
    private function extractDefinition($definition)
142
    {
143
        if (is_array($definition) && isset($definition['__definition'])) {
144 50
            $definition = $definition['__definition'];
145
        }
146 50
147 7
        return $definition;
148 7
    }
149
150 7
    private function extractTags($definition): array
151
    {
152
        if (is_array($definition) && isset($definition['__tags']) && is_array($definition['__tags'])) {
153
            $this->checkTags($definition['__tags']);
154 50
            return $definition['__tags'];
155 50
        }
156 41
157
        return [];
158 41
    }
159
160
    private function checkTags(array $tags): void
161 42
    {
162
        foreach ($tags as $tag) {
163 42
            if (!(is_string($tag))) {
164 1
                throw new InvalidConfigException('Invalid tag: ' . var_export($tag, true));
165
            }
166 42
        }
167
    }
168 48
169
    private function setTags(string $id, array $tags): void
170 48
    {
171 3
        foreach ($tags as $tag) {
172
            if (!isset($this->tags[$tag]) || !in_array($id, $this->tags[$tag])) {
173
                $this->tags[$tag][] = $id;
174 47
            }
175 38
        }
176
    }
177
178 17
    /**
179 5
     * Creates new instance by either interface name or alias.
180
     *
181
     * @param string $id The interface or an alias name that was previously registered.
182 12
     * @return mixed|object New built instance of the specified class.
183 8
     * @throws CircularReferenceException
184
     * @throws InvalidConfigException
185
     * @throws NotFoundException
186 4
     * @internal
187 3
     */
188
    private function build(string $id)
189
    {
190 1
        if ($this->isTagAlias($id)) {
191
            return $this->getTaggedServices($id);
192
        }
193
194
        if (isset($this->building[$id])) {
195
            throw new CircularReferenceException(sprintf(
196
                'Circular reference to "%s" detected while building: %s',
197
                $id,
198
                implode(',', array_keys($this->building))
199
            ));
200 50
        }
201
202 50
        $this->building[$id] = 1;
203 36
        $object = $this->buildInternal($id);
204
        unset($this->building[$id]);
205 42
206 42
        return $object;
207
    }
208 42
209
    private function isTagAlias(string $id): bool
210
    {
211
        return strpos($id, 'tag@') === 0;
212
    }
213
214
    private function getTaggedServices(string $tagAlias): array
215
    {
216
        $tag = substr($tagAlias, 4);
217
        $services = [];
218 36
        if (isset($this->tags[$tag])) {
219
            foreach ($this->tags[$tag] as $service) {
220 36
                $services[] = $this->get($service);
221 34
            }
222
        }
223 34
224
        return $services;
225
    }
226 3
227
228
    private function processDefinition($definition): void
229 55
    {
230
        if ($definition instanceof DeferredServiceProviderInterface) {
231 55
            $definition->register($this);
232 4
        }
233
    }
234 54
235
    private function validateDefinition($definition): void
236
    {
237
        if ($definition instanceof Reference || $definition instanceof DynamicReference) {
238
            return;
239
        }
240
241
        if (\is_string($definition)) {
242
            return;
243
        }
244
245
        if (\is_callable($definition)) {
246
            return;
247 4
        }
248
249 4
        if (\is_array($definition)) {
250
            return;
251 3
        }
252 1
253 1
        if (\is_object($definition)) {
254
            return;
255
        }
256 2
257
        throw new InvalidConfigException('Invalid definition:' . var_export($definition, true));
258 3
    }
259
260
    /**
261
     * @param string $id
262
     *
263
     * @return mixed|object
264
     * @throws InvalidConfigException
265
     * @throws NotFoundException
266
     */
267
    private function buildInternal(string $id)
268 4
    {
269
        if (!isset($this->definitions[$id])) {
270 4
            return $this->buildPrimitive($id);
271 3
        }
272
        $this->processDefinition($this->definitions[$id]);
273
        $definition = Normalizer::normalize($this->definitions[$id], $id);
274
275
        return $definition->resolve($this->rootContainer ?? $this);
276
    }
277 3
278
    /**
279
     * @param string $class
280 1
     *
281
     * @return mixed|object
282
     * @throws InvalidConfigException
283
     * @throws NotFoundException
284
     */
285
    private function buildPrimitive(string $class)
286
    {
287
        if (class_exists($class)) {
288
            $definition = new ArrayDefinition($class);
289
290
            return $definition->resolve($this->rootContainer ?? $this);
291
        }
292
293
        throw new NotFoundException("No definition for $class");
294
    }
295
296
    private function addProviders(array $providers): void
297
    {
298
        foreach ($providers as $provider) {
299
            $this->addProvider($provider);
300
        }
301
    }
302
303
    /**
304
     * Adds service provider to the container. Unless service provider is deferred
305
     * it would be immediately registered.
306
     *
307
     * @param string|array $providerDefinition
308
     *
309
     * @throws InvalidConfigException
310
     * @throws NotInstantiableException
311
     * @see ServiceProviderInterface
312
     * @see DeferredServiceProviderInterface
313
     */
314
    private function addProvider($providerDefinition): void
315
    {
316
        $provider = $this->buildProvider($providerDefinition);
317
318
        if ($provider instanceof DeferredServiceProviderInterface) {
319
            foreach ($provider->provides() as $id) {
320
                $this->definitions[$id] = $provider;
321
            }
322
        } else {
323
            $provider->register($this);
324
        }
325
    }
326
327
    /**
328
     * Builds service provider by definition.
329
     *
330
     * @param string|array $providerDefinition class name or definition of provider.
331
     * @return ServiceProviderInterface instance of service provider;
332
     *
333
     * @throws InvalidConfigException
334
     */
335
    private function buildProvider($providerDefinition): ServiceProviderInterface
336
    {
337
        $provider = Normalizer::normalize($providerDefinition)->resolve($this);
338
        if (!($provider instanceof ServiceProviderInterface)) {
339
            throw new InvalidConfigException(
340
                'Service provider should be an instance of ' . ServiceProviderInterface::class
341
            );
342
        }
343
344
        return $provider;
345
    }
346
}
347