Passed
Pull Request — master (#134)
by Dmitriy
11:48
created

Container::buildProvider()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 2.5

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 10
ccs 1
cts 2
cp 0.5
crap 2.5
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 57
    public function __construct(
52
        array $definitions = [],
53
        array $providers = [],
54
        ContainerInterface $rootContainer = null
55
    ) {
56 57
        $this->setMultiple($definitions);
57 56
        $this->addProviders($providers);
58 55
        if ($rootContainer !== null) {
59 5
            $this->delegateLookup($rootContainer);
60
        }
61 55
    }
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 51
    public function get($id)
87
    {
88 51
        $id = $this->getId($id);
89 51
        if (!isset($this->instances[$id])) {
90 51
            $this->instances[$id] = $this->build($id);
91
        }
92
93 42
        return $this->instances[$id];
94
    }
95
96
    protected function hasDefinition($id): bool
97
    {
98
        return isset($this->definitions[$id]);
99
    }
100 5
101
    /**
102 5
     * Delegate service lookup to another container.
103 5
     * @param ContainerInterface $container
104
     */
105
    protected function delegateLookup(ContainerInterface $container): void
106 5
    {
107 5
        if ($this->rootContainer === null) {
108
            $this->rootContainer = new CompositeContainer();
109
        }
110
111
        $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...
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

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