Passed
Push — master ( d826f4...1a9eea )
by Alexander
01:58
created

Container   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 251
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 7
Bugs 0 Features 0
Metric Value
eloc 63
dl 0
loc 251
ccs 76
cts 76
cp 1
rs 10
c 7
b 0
f 0
wmc 28

14 Methods

Rating   Name   Duplication   Size   Complexity  
A get() 0 7 2
A set() 0 5 1
A addProviders() 0 4 2
A has() 0 3 2
A buildProvider() 0 8 1
A delegateLookup() 0 10 3
A processDefinition() 0 4 2
A buildInternal() 0 9 2
A setMultiple() 0 7 3
A buildPrimitive() 0 9 2
A addProvider() 0 10 3
A __construct() 0 12 1
A setDefaultDefinitions() 0 5 1
A build() 0 18 3
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\ArrayDefinition;
11
use Yiisoft\Factory\Definitions\Normalizer;
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\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 71
    public function __construct(
51
        array $definitions = [],
52
        array $providers = [],
53
        ContainerInterface $rootContainer = null
54
    ) {
55 71
        $this->delegateLookup($rootContainer);
56 71
        $this->setDefaultDefinitions();
57 71
        $this->setMultiple($definitions);
58 69
        $this->addProviders($providers);
59
60
        # Prevent circular reference to ContainerInterface
61 67
        $this->get(ContainerInterface::class);
62 67
    }
63
64 71
    private function setDefaultDefinitions(): void
65
    {
66 71
        $this->definitions = [
67 71
            ContainerInterface::class => $this->rootContainer ?? $this,
68 71
            Injector::class => new Injector($this),
69
        ];
70 71
    }
71
72
    /**
73
     * Returns a value indicating whether the container has the definition of the specified name.
74
     * @param string $id class name, interface name or alias name
75
     * @return bool whether the container is able to provide instance of class specified.
76
     * @see set()
77
     */
78 27
    public function has($id): bool
79
    {
80 27
        return isset($this->definitions[$id]) || class_exists($id);
81
    }
82
83
    /**
84
     * Returns an instance by either interface name or alias.
85
     *
86
     * Same instance of the class will be returned each time this method is called.
87
     *
88
     * @param string $id The interface or an alias name that was previously registered.
89
     * @return object An instance of the requested interface.
90
     * @throws CircularReferenceException
91
     * @throws InvalidConfigException
92
     * @throws NotFoundException
93
     * @throws NotInstantiableException
94
     */
95 68
    public function get($id)
96
    {
97 68
        if (!isset($this->instances[$id])) {
98 68
            $this->instances[$id] = $this->build($id);
99
        }
100
101 68
        return $this->instances[$id];
102
    }
103
104
    /**
105
     * Delegate service lookup to another container.
106
     * @param ContainerInterface $container
107
     */
108 71
    protected function delegateLookup(?ContainerInterface $container): void
109
    {
110 71
        if ($container === null) {
111 71
            return;
112
        }
113 7
        if ($this->rootContainer === null) {
114 7
            $this->rootContainer = new CompositeContainer();
115
        }
116
117 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

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