Passed
Push — master ( 4042b0...0955cf )
by Alexander
01:38
created

Container::resolveRecursiveContainer()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 2
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\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
        $this->addProviders($providers);
58 62
        $this->resolveRecursiveContainer();
59 62
    }
60
61 62
    private function resolveRecursiveContainer(): void
62
    {
63 62
        if ($this->has(ContainerInterface::class)) {
64 2
            $this->get(ContainerInterface::class);
65
        } else {
66 62
            $this->set(ContainerInterface::class, $this->rootContainer ?? $this);
67
        }
68 62
    }
69
70
    /**
71
     * Returns a value indicating whether the container has the definition of the specified name.
72
     * @param string $id class name, interface name or alias name
73
     * @return bool whether the container is able to provide instance of class specified.
74
     * @see set()
75
     */
76 62
    public function has($id): bool
77
    {
78 62
        return isset($this->definitions[$id]) || class_exists($id);
79
    }
80
81
    /**
82
     * Returns an instance by either interface name or alias.
83
     *
84
     * Same instance of the class will be returned each time this method is called.
85
     *
86
     * @param string $id The interface or an alias name that was previously registered.
87
     * @return object An instance of the requested interface.
88
     * @throws CircularReferenceException
89
     * @throws InvalidConfigException
90
     * @throws NotFoundException
91
     * @throws NotInstantiableException
92
     */
93 57
    public function get($id)
94
    {
95 57
        if (!isset($this->instances[$id])) {
96 57
            $this->instances[$id] = $this->build($id);
97
        }
98
99 48
        return $this->instances[$id];
100
    }
101
102
    /**
103
     * Delegate service lookup to another container.
104
     * @param ContainerInterface $container
105
     */
106 65
    protected function delegateLookup(?ContainerInterface $container): void
107
    {
108 65
        if ($container === null) {
109 65
            return;
110
        }
111 7
        if ($this->rootContainer === null) {
112 7
            $this->rootContainer = new CompositeContainer();
113
        }
114
115 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

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