Passed
Pull Request — master (#143)
by Dmitriy
10:36
created

Container::buildProvider()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.1481

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 10
ccs 4
cts 6
cp 0.6667
crap 2.1481
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\Factory;
11
use Yiisoft\Factory\Definitions\DynamicReference;
12
use Yiisoft\Factory\Definitions\Reference;
13
use Yiisoft\Factory\Exceptions\CircularReferenceException;
14
use Yiisoft\Factory\Exceptions\InvalidConfigException;
15
use Yiisoft\Factory\Exceptions\NotFoundException;
16
use Yiisoft\Factory\Exceptions\NotInstantiableException;
17
use Yiisoft\Factory\Definitions\Normalizer;
18
use Yiisoft\Factory\Definitions\ArrayDefinition;
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 ?CompositeContainer $rootContainer = null;
41
42
    private Factory $factory;
43
44
    /**
45
     * Container constructor.
46
     *
47
     * @param array $definitions Definitions to put into container.
48
     * @param ServiceProviderInterface[]|string[] $providers Service providers to get definitions from.
49
     *
50
     * @param ContainerInterface|null $rootContainer Root container to delegate lookup to in case definition
51 56
     * is not found in current container.
52
     * @throws InvalidConfigException
53
     */
54
    public function __construct(
55
        array $definitions = [],
56 56
        array $providers = [],
57 55
        ContainerInterface $rootContainer = null
58 54
    ) {
59 5
        $this->factory = new Factory();
60
        $this->setMultiple($definitions);
61 54
        $this->addProviders($providers);
62
        if ($rootContainer !== null) {
63
            $this->delegateLookup($rootContainer);
64
        }
65
    }
66
67
    /**
68
     * Returns a value indicating whether the container has the definition of the specified name.
69 24
     * @param string $id class name, interface name or alias name
70
     * @return bool whether the container is able to provide instance of class specified.
71 24
     * @see set()
72
     */
73
    public function has($id): bool
74
    {
75
        return isset($this->definitions[$id]) || class_exists($id);
76
    }
77
78
    /**
79
     * Returns an instance by either interface name or alias.
80
     *
81
     * Same instance of the class will be returned each time this method is called.
82
     *
83
     * @param string|Reference $id The interface or an alias name that was previously registered.
84
     * @return object An instance of the requested interface.
85
     * @throws CircularReferenceException
86 50
     * @throws InvalidConfigException
87
     * @throws NotFoundException
88 50
     * @throws NotInstantiableException
89 50
     */
90
    public function get($id)
91
    {
92 41
        if (!isset($this->instances[$id])) {
93
            $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

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

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