Passed
Pull Request — master (#150)
by Andrii
12:58
created

Container::getInjector()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 7
ccs 2
cts 2
cp 1
crap 2
rs 10
c 0
b 0
f 0
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
use Yiisoft\Injector\Injector;
19
20
/**
21
 * Container implements a [dependency injection](http://en.wikipedia.org/wiki/Dependency_injection) container.
22
 */
23
final class Container extends AbstractContainerConfigurator implements ContainerInterface
24
{
25
    /**
26
     * @var array object definitions indexed by their types
27
     */
28
    private array $definitions = [];
29
    /**
30
     * @var array used to collect ids instantiated during build
31
     * to detect circular references
32
     */
33
    private array $building = [];
34
35
    /**
36
     * @var object[]
37
     */
38
    private array $instances = [];
39
40
    private ?ContainerInterface $rootContainer = null;
41
42
    /**
43
     * Container constructor.
44
     *
45
     * @param array $definitions Definitions to put into container.
46
     * @param ServiceProviderInterface[]|string[] $providers Service providers to get definitions from.
47
     *
48
     * @param ContainerInterface|null $rootContainer Root container to delegate lookup to in case definition
49
     * is not found in current container.
50
     * @throws InvalidConfigException
51 57
     */
52
    public function __construct(
53
        array $definitions = [],
54
        array $providers = [],
55
        ContainerInterface $rootContainer = null
56 57
    ) {
57 55
        $this->setMultiple($definitions);
58 54
        if (!$this->has(ContainerInterface::class)) {
59 5
            $this->set(ContainerInterface::class, $this);
60
        }
61 54
        $this->addProviders($providers);
62
        if ($rootContainer !== null) {
63
            $this->delegateLookup($rootContainer);
64
        }
65
    }
66
67
    private $injector;
68
69 24
    public function getInjector()
70
    {
71 24
        if ($this->injector === null) {
72
            $this->injector = new Injector($this);
73
        }
74
75
        return $this->injector;
76
    }
77
78
    /**
79
     * Returns a value indicating whether the container has the definition of the specified name.
80
     * @param string $id class name, interface name or alias name
81
     * @return bool whether the container is able to provide instance of class specified.
82
     * @see set()
83
     */
84
    public function has($id): bool
85
    {
86 50
        return isset($this->definitions[$id]) || class_exists($id);
87
    }
88 50
89 50
    /**
90
     * Returns an instance by either interface name or alias.
91
     *
92 41
     * Same instance of the class will be returned each time this method is called.
93
     *
94
     * @param string|Reference $id The interface or an alias name that was previously registered.
95
     * @return object An instance of the requested interface.
96
     * @throws CircularReferenceException
97
     * @throws InvalidConfigException
98
     * @throws NotFoundException
99 5
     * @throws NotInstantiableException
100
     */
101 5
    public function get($id)
102 5
    {
103
        if (!isset($this->instances[$id])) {
104
            $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

104
            $this->instances[$id] = $this->build(/** @scrutinizer ignore-type */ $id);
Loading history...
105 5
        }
106 5
107
        return $this->instances[$id];
108
    }
109
110
    /**
111
     * Delegate service lookup to another container.
112
     * @param ContainerInterface $container
113
     */
114
    protected function delegateLookup(ContainerInterface $container): void
115 48
    {
116
        if ($this->rootContainer === null) {
117 48
            $this->rootContainer = new CompositeContainer();
118 47
        }
119 47
120 47
        $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

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

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