Passed
Pull Request — master (#144)
by Dmitriy
18:49 queued 03:55
created

Container::set()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 6
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 8
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 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
        if ($this->isTagAlias($id)) {
76
            $tag = substr($id, 4);
77
            return isset($this->tags[$tag]);
78
        }
79
80
        return isset($this->definitions[$id]) || class_exists($id);
81
    }
82
83
    /**
84
     * Returns an instance by either interface name or alias.
85
     *
86 50
     * Same instance of the class will be returned each time this method is called.
87
     *
88 50
     * @param string|Reference $id The interface or an alias name that was previously registered.
89 50
     * @return object An instance of the requested interface.
90
     * @throws CircularReferenceException
91
     * @throws InvalidConfigException
92 41
     * @throws NotFoundException
93
     * @throws NotInstantiableException
94
     */
95
    public function get($id)
96
    {
97
        if (!isset($this->instances[$id])) {
98
            $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

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

114
        $this->rootContainer->/** @scrutinizer ignore-call */ 
115
                              attach($container);
Loading history...
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

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