Passed
Push — master ( 25ca8a...f7ffed )
by Alexander
02:24 queued 42s
created

Container::buildPrimitive()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

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

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