Passed
Pull Request — master (#170)
by Andrii
03:46 queued 01:52
created

Container::setMultiple()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

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

111
        $this->rootContainer->/** @scrutinizer ignore-call */ 
112
                              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...
112 7
    }
113
114
    /**
115
     * Sets a definition to the container. Definition may be defined multiple ways.
116
     * @param string $id
117
     * @param mixed $definition
118
     * @throws InvalidConfigException
119
     * @see `Normalizer::normalize()`
120
     */
121 64
    protected function set(string $id, $definition): void
122
    {
123 64
        Normalizer::validate($definition);
124 63
        unset($this->instances[$id]);
125 63
        $this->definitions[$id] = $definition;
126 63
    }
127
128
    /**
129
     * Sets multiple definitions at once.
130
     * @param array $config definitions indexed by their ids
131
     * @throws InvalidConfigException
132
     */
133 65
    protected function setMultiple(array $config): void
134
    {
135 65
        foreach ($config as $id => $definition) {
136 54
            if (!is_string($id)) {
137 1
                throw new InvalidConfigException('Key must be a string');
138
            }
139 53
            $this->set($id, $definition);
140
        }
141 63
    }
142
143
    /**
144
     * Creates new instance by either interface name or alias.
145
     *
146
     * @param string $id The interface or an alias name that was previously registered.
147
     * @return object New built instance of the specified class.
148
     * @throws CircularReferenceException
149
     * @throws InvalidConfigException
150
     * @throws NotFoundException
151
     * @internal
152
     */
153 62
    private function build(string $id)
154
    {
155 62
        if ($id === Injector::class) {
156 12
            return new Injector($this);
157
        }
158 62
        if (isset($this->building[$id])) {
159 9
            if ($id === ContainerInterface::class) {
160 2
                return $this;
161
            }
162 7
            throw new CircularReferenceException(sprintf(
163 7
                'Circular reference to "%s" detected while building: %s',
164
                $id,
165 7
                implode(',', array_keys($this->building))
166
            ));
167
        }
168
169 62
        $this->building[$id] = 1;
170 62
        $object = $this->buildInternal($id);
171 62
        unset($this->building[$id]);
172
173 62
        return $object;
174
    }
175
176
    /**
177
     * @param mixed $definition
178
     */
179 62
    private function processDefinition($definition): void
180
    {
181 62
        if ($definition instanceof DeferredServiceProviderInterface) {
182 1
            $definition->register($this);
183
        }
184 62
    }
185
186
    /**
187
     * @param string $id
188
     *
189
     * @return mixed|object
190
     * @throws InvalidConfigException
191
     * @throws NotFoundException
192
     */
193 62
    private function buildInternal(string $id)
194
    {
195 62
        if (!isset($this->definitions[$id])) {
196 41
            return $this->buildPrimitive($id);
197
        }
198 62
        $this->processDefinition($this->definitions[$id]);
199 62
        $definition = Normalizer::normalize($this->definitions[$id], $id);
200
201 62
        return $definition->resolve($this->rootContainer ?? $this);
202
    }
203
204
    /**
205
     * @param string $class
206
     *
207
     * @return mixed|object
208
     * @throws InvalidConfigException
209
     * @throws NotFoundException
210
     */
211 41
    private function buildPrimitive(string $class)
212
    {
213 41
        if (class_exists($class)) {
214 39
            $definition = new ArrayDefinition($class);
215
216 39
            return $definition->resolve($this->rootContainer ?? $this);
217
        }
218
219 4
        throw new NotFoundException("No definition for $class");
220
    }
221
222 63
    private function addProviders(array $providers): void
223
    {
224 63
        foreach ($providers as $provider) {
225 5
            $this->addProvider($provider);
226
        }
227 62
    }
228
229
    /**
230
     * Adds service provider to the container. Unless service provider is deferred
231
     * it would be immediately registered.
232
     *
233
     * @param mixed $providerDefinition
234
     *
235
     * @throws InvalidConfigException
236
     * @throws NotInstantiableException
237
     * @see ServiceProviderInterface
238
     * @see DeferredServiceProviderInterface
239
     */
240 5
    private function addProvider($providerDefinition): void
241
    {
242 5
        $provider = $this->buildProvider($providerDefinition);
243
244 4
        if ($provider instanceof DeferredServiceProviderInterface) {
245 1
            foreach ($provider->provides() as $id) {
246 1
                $this->definitions[$id] = $provider;
247
            }
248
        } else {
249 3
            $provider->register($this);
250
        }
251 4
    }
252
253
    /**
254
     * Builds service provider by definition.
255
     *
256
     * @param mixed $providerDefinition class name or definition of provider.
257
     * @return ServiceProviderInterface instance of service provider;
258
     *
259
     * @throws InvalidConfigException
260
     */
261 5
    private function buildProvider($providerDefinition): ServiceProviderInterface
262
    {
263 5
        $provider = Normalizer::normalize($providerDefinition)->resolve($this);
264
        assert($provider instanceof ServiceProviderInterface, new InvalidConfigException(
265
            'Service provider should be an instance of ' . ServiceProviderInterface::class
266
        ));
267
268 4
        return $provider;
269
    }
270
}
271