Passed
Push — github-actions ( e63dce )
by Alexander
03:10
created

Container   A

Complexity

Total Complexity 35

Size/Duplication

Total Lines 262
Duplicated Lines 0 %

Test Coverage

Coverage 97.56%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 35
eloc 67
c 1
b 0
f 0
dl 0
loc 262
ccs 80
cts 82
cp 0.9756
rs 9.6

15 Methods

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

106
        $this->rootContainer->/** @scrutinizer ignore-call */ 
107
                              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...
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

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