Passed
Push — master ( 80f33b...29508b )
by Alexander
21:23 queued 19:30
created

Container   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 246
Duplicated Lines 0 %

Test Coverage

Coverage 97.37%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 63
c 2
b 0
f 0
dl 0
loc 246
ccs 74
cts 76
cp 0.9737
rs 10
wmc 30

13 Methods

Rating   Name   Duplication   Size   Complexity  
A set() 0 5 1
A setMultiple() 0 7 3
A delegateLookup() 0 7 2
A __construct() 0 16 3
A get() 0 7 2
A addProviders() 0 4 2
A has() 0 3 2
A buildProvider() 0 10 2
A build() 0 21 4
A processDefinition() 0 4 2
A buildInternal() 0 9 2
A buildPrimitive() 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\Reference;
11
use Yiisoft\Factory\Exceptions\CircularReferenceException;
12
use Yiisoft\Factory\Exceptions\InvalidConfigException;
13
use Yiisoft\Factory\Exceptions\NotFoundException;
14
use Yiisoft\Factory\Exceptions\NotInstantiableException;
15
use Yiisoft\Factory\Definitions\Normalizer;
16
use Yiisoft\Factory\Definitions\ArrayDefinition;
17
use Yiisoft\Injector\Injector;
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 ?CompositeContainer $rootContainer = null;
40
41
    /**
42
     * Container constructor.
43
     *
44
     * @param array $definitions Definitions to put into container.
45
     * @param ServiceProviderInterface[]|string[] $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 64
    public function __construct(
52
        array $definitions = [],
53
        array $providers = [],
54
        ContainerInterface $rootContainer = null
55
    ) {
56 64
        $this->setMultiple($definitions);
57 62
        if (!$this->has(ContainerInterface::class)) {
58 62
            $this->set(ContainerInterface::class, $rootContainer ?? $this);
59
        }
60
61 62
        $this->addProviders($providers);
62 61
        if ($rootContainer !== null) {
63 8
            $this->delegateLookup($rootContainer);
64
        }
65
        # Prevent circular reference to ContainerInterface
66 61
        $this->get(ContainerInterface::class);
67 61
    }
68
69
    /**
70
     * Returns a value indicating whether the container has the definition of the specified name.
71
     * @param string $id class name, interface name or alias name
72
     * @return bool whether the container is able to provide instance of class specified.
73
     * @see set()
74
     */
75 62
    public function has($id): bool
76
    {
77 62
        return isset($this->definitions[$id]) || class_exists($id);
78
    }
79
80
    /**
81
     * Returns an instance by either interface name or alias.
82
     *
83
     * Same instance of the class will be returned each time this method is called.
84
     *
85
     * @param string $id The interface or an alias name that was previously registered.
86
     * @return object An instance of the requested interface.
87
     * @throws CircularReferenceException
88
     * @throws InvalidConfigException
89
     * @throws NotFoundException
90
     * @throws NotInstantiableException
91
     */
92 61
    public function get($id)
93
    {
94 61
        if (!isset($this->instances[$id])) {
95 61
            $this->instances[$id] = $this->build($id);
96
        }
97
98 61
        return $this->instances[$id];
99
    }
100
101
    /**
102
     * Delegate service lookup to another container.
103
     * @param ContainerInterface $container
104
     */
105 8
    protected function delegateLookup(ContainerInterface $container): void
106
    {
107 8
        if ($this->rootContainer === null) {
108 8
            $this->rootContainer = new CompositeContainer();
109
        }
110
111 8
        $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 8
    }
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 63
    protected function set(string $id, $definition): void
122
    {
123 63
        Normalizer::validate($definition);
124 62
        $this->instances[$id] = null;
125 62
        $this->definitions[$id] = $definition;
126 62
    }
127
128
    /**
129
     * Sets multiple definitions at once.
130
     * @param array $config definitions indexed by their ids
131
     * @throws InvalidConfigException
132
     */
133 64
    protected function setMultiple(array $config): void
134
    {
135 64
        foreach ($config as $id => $definition) {
136 53
            if (!is_string($id)) {
137 1
                throw new InvalidConfigException('Key must be a string');
138
            }
139 52
            $this->set((string)$id, $definition);
140
        }
141 62
    }
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 61
    private function build(string $id)
154
    {
155 61
        if ($id === Injector::class) {
156 11
            return new Injector($this);
157
        }
158 61
        if (isset($this->building[$id])) {
159 10
            if ($id === ContainerInterface::class) {
160 3
                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 61
        $this->building[$id] = 1;
170 61
        $object = $this->buildInternal($id);
171 61
        unset($this->building[$id]);
172
173 61
        return $object;
174
    }
175
176 61
    private function processDefinition($definition): void
177
    {
178 61
        if ($definition instanceof DeferredServiceProviderInterface) {
179 1
            $definition->register($this);
180
        }
181 61
    }
182
183
    /**
184
     * @param string $id
185
     *
186
     * @return mixed|object
187
     * @throws InvalidConfigException
188
     * @throws NotFoundException
189
     */
190 61
    private function buildInternal(string $id)
191
    {
192 61
        if (!isset($this->definitions[$id])) {
193 41
            return $this->buildPrimitive($id);
194
        }
195 61
        $this->processDefinition($this->definitions[$id]);
196 61
        $definition = Normalizer::normalize($this->definitions[$id], $id);
197
198 61
        return $definition->resolve($this->rootContainer ?? $this);
199
    }
200
201
    /**
202
     * @param string $class
203
     *
204
     * @return mixed|object
205
     * @throws InvalidConfigException
206
     * @throws NotFoundException
207
     */
208 41
    private function buildPrimitive(string $class)
209
    {
210 41
        if (class_exists($class)) {
211 39
            $definition = new ArrayDefinition($class);
212
213 39
            return $definition->resolve($this->rootContainer ?? $this);
214
        }
215
216 4
        throw new NotFoundException("No definition for $class");
217
    }
218
219 62
    private function addProviders(array $providers): void
220
    {
221 62
        foreach ($providers as $provider) {
222 5
            $this->addProvider($provider);
223
        }
224 61
    }
225
226
    /**
227
     * Adds service provider to the container. Unless service provider is deferred
228
     * it would be immediately registered.
229
     *
230
     * @param string|array $providerDefinition
231
     *
232
     * @throws InvalidConfigException
233
     * @throws NotInstantiableException
234
     * @see ServiceProviderInterface
235
     * @see DeferredServiceProviderInterface
236
     */
237 5
    private function addProvider($providerDefinition): void
238
    {
239 5
        $provider = $this->buildProvider($providerDefinition);
240
241 4
        if ($provider instanceof DeferredServiceProviderInterface) {
242 1
            foreach ($provider->provides() as $id) {
243 1
                $this->definitions[$id] = $provider;
244
            }
245
        } else {
246 3
            $provider->register($this);
247
        }
248 4
    }
249
250
    /**
251
     * Builds service provider by definition.
252
     *
253
     * @param string|array $providerDefinition class name or definition of provider.
254
     * @return ServiceProviderInterface instance of service provider;
255
     *
256
     * @throws InvalidConfigException
257
     */
258 5
    private function buildProvider($providerDefinition): ServiceProviderInterface
259
    {
260 5
        $provider = Normalizer::normalize($providerDefinition)->resolve($this);
261 4
        if (!($provider instanceof ServiceProviderInterface)) {
262
            throw new InvalidConfigException(
263
                'Service provider should be an instance of ' . ServiceProviderInterface::class
264
            );
265
        }
266
267 4
        return $provider;
268
    }
269
}
270