Passed
Pull Request — master (#134)
by Dmitriy
13:23
created

Container   A

Complexity

Total Complexity 36

Size/Duplication

Total Lines 269
Duplicated Lines 0 %

Test Coverage

Coverage 97.56%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 69
dl 0
loc 269
ccs 80
cts 82
cp 0.9756
rs 9.52
c 2
b 0
f 0
wmc 36

16 Methods

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

113
        $this->rootContainer->/** @scrutinizer ignore-call */ 
114
                              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

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