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