Passed
Pull Request — master (#167)
by Dmitriy
29:21 queued 14:33
created

Container::setInjector()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 1
eloc 2
c 1
b 1
f 0
nc 1
nop 1
dl 0
loc 4
ccs 1
cts 1
cp 1
crap 1
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\Definitions\ArrayDefinition;
11
use Yiisoft\Factory\Definitions\Normalizer;
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\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
    public function __construct(
51 64
        array $definitions = [],
52
        array $providers = [],
53
        ContainerInterface $rootContainer = null
54
    )
55
    {
56 64
        $this->set(ContainerInterface::class, $rootContainer ?? $this);
57 62
        $this->setMultiple($definitions);
58 62
59
        $this->setInjector($rootContainer ?? $this);
60
        $this->addProviders($providers);
61 62
        if ($rootContainer !== null) {
62 61
            $this->delegateLookup($rootContainer);
63 8
        }
64
        # Prevent circular reference to ContainerInterface
65
        $container = $this->get(ContainerInterface::class);
66 61
        $this->setInjector($container);
67 61
    }
68
69
    /**
70
     * Returns a value indicating whether the container has the definition of the specified name.
71
     * @param string $id class name, interface name or alias name
72
     * @return bool whether the container is able to provide instance of class specified.
73
     * @see set()
74
     */
75 62
    public function has($id): bool
76
    {
77 62
        return isset($this->definitions[$id]) || class_exists($id);
78
    }
79
80
    /**
81
     * Returns an instance by either interface name or alias.
82
     *
83
     * Same instance of the class will be returned each time this method is called.
84
     *
85
     * @param string $id The interface or an alias name that was previously registered.
86
     * @return object An instance of the requested interface.
87
     * @throws CircularReferenceException
88
     * @throws InvalidConfigException
89
     * @throws NotFoundException
90
     * @throws NotInstantiableException
91
     */
92 61
    public function get($id)
93
    {
94 61
        if (!isset($this->instances[$id])) {
95 61
            $this->instances[$id] = $this->build($id);
96
        }
97
98 61
        return $this->instances[$id];
99
    }
100
101
    /**
102
     * Delegate service lookup to another container.
103
     * @param ContainerInterface $container
104
     */
105 8
    protected function delegateLookup(ContainerInterface $container): void
106
    {
107 8
        if ($this->rootContainer === null) {
108 8
            $this->rootContainer = new CompositeContainer();
109
        }
110
111 8
        $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...
112 8
    }
113
114
    /**
115
     * Sets a definition to the container. Definition may be defined multiple ways.
116
     * @param string $id
117
     * @param mixed $definition
118
     * @throws InvalidConfigException
119
     * @see `Normalizer::normalize()`
120
     */
121 63
    protected function set(string $id, $definition): void
122
    {
123 63
        Normalizer::validate($definition);
124 62
        $this->instances[$id] = null;
125 62
        $this->definitions[$id] = $definition;
126 62
    }
127
128
    /**
129
     * Sets multiple definitions at once.
130
     * @param array $config definitions indexed by their ids
131
     * @throws InvalidConfigException
132
     */
133 64
    protected function setMultiple(array $config): void
134
    {
135 64
        foreach ($config as $id => $definition) {
136 53
            if (!is_string($id)) {
137 1
                throw new InvalidConfigException('Key must be a string');
138
            }
139 52
            $this->set((string)$id, $definition);
140
        }
141 62
    }
142
143
    /**
144
     * Creates new instance by either interface name or alias.
145
     *
146
     * @param string $id The interface or an alias name that was previously registered.
147
     * @return object New built instance of the specified class.
148
     * @throws CircularReferenceException
149
     * @throws InvalidConfigException
150
     * @throws NotFoundException
151
     * @internal
152
     */
153 61
    private function build(string $id)
154
    {
155 61
        if (isset($this->building[$id])) {
156 11
            if ($id === ContainerInterface::class) {
157
                return $this;
158 61
            }
159 10
            throw new CircularReferenceException(sprintf(
160 3
                'Circular reference to "%s" detected while building: %s',
161
                $id,
162 7
                implode(',', array_keys($this->building))
163 7
            ));
164
        }
165 7
166
        $this->building[$id] = 1;
167
        $object = $this->buildInternal($id);
168
        unset($this->building[$id]);
169 61
170 61
        return $object;
171 61
    }
172
173 61
    private function processDefinition($definition): void
174
    {
175
        if ($definition instanceof DeferredServiceProviderInterface) {
176 61
            $definition->register($this);
177
        }
178 61
    }
179 1
180
    /**
181 61
     * @param string $id
182
     *
183
     * @return mixed|object
184
     * @throws InvalidConfigException
185
     * @throws NotFoundException
186
     */
187
    private function buildInternal(string $id)
188
    {
189
        if (!isset($this->definitions[$id])) {
190 61
            return $this->buildPrimitive($id);
191
        }
192 61
        $this->processDefinition($this->definitions[$id]);
193 41
        $definition = Normalizer::normalize($this->definitions[$id], $id);
194
195 61
        return $definition->resolve($this->rootContainer ?? $this);
196 61
    }
197
198 61
    /**
199
     * @param string $class
200
     *
201
     * @return mixed|object
202
     * @throws InvalidConfigException
203
     * @throws NotFoundException
204
     */
205
    private function buildPrimitive(string $class)
206
    {
207
        if (class_exists($class)) {
208 41
            $definition = new ArrayDefinition($class);
209
210 41
            return $definition->resolve($this->rootContainer ?? $this);
211 39
        }
212
213 39
        throw new NotFoundException("No definition for $class");
214
    }
215
216 4
    private function addProviders(array $providers): void
217
    {
218
        foreach ($providers as $provider) {
219 62
            $this->addProvider($provider);
220
        }
221 62
    }
222 5
223
    /**
224 61
     * Adds service provider to the container. Unless service provider is deferred
225
     * it would be immediately registered.
226
     *
227
     * @param string|array $providerDefinition
228
     *
229
     * @throws InvalidConfigException
230
     * @throws NotInstantiableException
231
     * @see ServiceProviderInterface
232
     * @see DeferredServiceProviderInterface
233
     */
234
    private function addProvider($providerDefinition): void
235
    {
236
        $provider = $this->buildProvider($providerDefinition);
237 5
238
        if ($provider instanceof DeferredServiceProviderInterface) {
239 5
            foreach ($provider->provides() as $id) {
240
                $this->definitions[$id] = $provider;
241 4
            }
242 1
        } else {
243 1
            $provider->register($this);
244
        }
245
    }
246 3
247
    /**
248 4
     * Builds service provider by definition.
249
     *
250
     * @param string|array $providerDefinition class name or definition of provider.
251
     * @return ServiceProviderInterface instance of service provider;
252
     *
253
     * @throws InvalidConfigException
254
     */
255
    private function buildProvider($providerDefinition): ServiceProviderInterface
256
    {
257
        $provider = Normalizer::normalize($providerDefinition)->resolve($this);
258 5
        if (!($provider instanceof ServiceProviderInterface)) {
259
            throw new InvalidConfigException(
260 5
                'Service provider should be an instance of ' . ServiceProviderInterface::class
261 4
            );
262
        }
263
264
        return $provider;
265
    }
266
267 4
    private function setInjector(ContainerInterface $container): void
268
    {
269
        $injector = new Injector($container);
270
        $this->set(Injector::class, $injector);
271
    }
272
}
273