Passed
Push — master ( d535a9...0c2aed )
by Alexander
01:35
created

Container::get()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 7
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\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[]|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 57
    public function __construct(
52
        array $definitions = [],
53
        array $providers = [],
54
        ContainerInterface $rootContainer = null
55
    ) {
56 57
        $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
        if (!isset($this->instances[$id])) {
89 50
            $this->instances[$id] = $this->build($id);
0 ignored issues
show
Bug introduced by
It seems like $id can also be of type Yiisoft\Factory\Definitions\Reference; however, parameter $id of Yiisoft\Di\Container::build() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

89
            $this->instances[$id] = $this->build(/** @scrutinizer ignore-type */ $id);
Loading history...
90
        }
91
92 41
        return $this->instances[$id];
93
    }
94
95
    /**
96
     * Delegate service lookup to another container.
97
     * @param ContainerInterface $container
98
     */
99 5
    protected function delegateLookup(ContainerInterface $container): void
100
    {
101 5
        if ($this->rootContainer === null) {
102 5
            $this->rootContainer = new CompositeContainer();
103
        }
104
105 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

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

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