Passed
Pull Request — master (#177)
by Andrii
13:21
created

Container::setDefaults()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 5
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 67
    public function __construct(
51
        array $definitions = [],
52
        array $providers = [],
53
        ContainerInterface $rootContainer = null
54
    ) {
55 67
        $this->delegateLookup($rootContainer);
56 67
        $this->setDefaults();
57 65
        $this->setMultiple($definitions);
58 65
        $this->addProviders($providers);
59
60 65
        # Prevent circular reference to ContainerInterface
61
        $this->get(ContainerInterface::class);
62
    }
63 63
64 63
    private function setDefaults(): void
65
    {
66
        $this->definitions = [
67
            ContainerInterface::class => $this->rootContainer ?? $this,
68
            Injector::class => new Injector($this),
69
        ];
70
    }
71
72 65
    /**
73
     * Returns a value indicating whether the container has the definition of the specified name.
74 65
     * @param string $id class name, interface name or alias name
75
     * @return bool whether the container is able to provide instance of class specified.
76
     * @see set()
77
     */
78
    public function has($id): bool
79
    {
80
        return isset($this->definitions[$id]) || class_exists($id);
81
    }
82
83
    /**
84
     * Returns an instance by either interface name or alias.
85
     *
86
     * Same instance of the class will be returned each time this method is called.
87
     *
88
     * @param string $id The interface or an alias name that was previously registered.
89 64
     * @return object An instance of the requested interface.
90
     * @throws CircularReferenceException
91 64
     * @throws InvalidConfigException
92 64
     * @throws NotFoundException
93
     * @throws NotInstantiableException
94
     */
95 64
    public function get($id)
96
    {
97
        if (!isset($this->instances[$id])) {
98
            $this->instances[$id] = $this->build($id);
99
        }
100
101
        return $this->instances[$id];
102 67
    }
103
104 67
    /**
105 67
     * Delegate service lookup to another container.
106
     * @param ContainerInterface $container
107 7
     */
108 7
    protected function delegateLookup(?ContainerInterface $container): void
109
    {
110
        if ($container === null) {
111 7
            return;
112 7
        }
113
        if ($this->rootContainer === null) {
114
            $this->rootContainer = new CompositeContainer();
115
        }
116
117
        $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

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