Passed
Pull Request — master (#136)
by Dmitriy
16:16
created

Container::getId()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 1
nc 2
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 2
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
        if (!isset($this->instances[$id])) {
89 51
            $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 51
        }
91
92
        return $this->instances[$id];
93 42
    }
94
95
    /**
96
     * Delegate service lookup to another container.
97
     * @param ContainerInterface $container
98
     */
99
    protected function delegateLookup(ContainerInterface $container): void
100 5
    {
101
        if ($this->rootContainer === null) {
102 5
            $this->rootContainer = new CompositeContainer();
103 5
        }
104
105
        $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 5
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
    protected function set(string $id, $definition): void
116 49
    {
117
        $this->validateDefinition($definition);
118 49
        $this->instances[$id] = null;
119 48
        $this->definitions[$id] = $definition;
120 48
    }
121 48
122
    /**
123
     * Sets multiple definitions at once.
124
     * @param array $config definitions indexed by their ids
125
     * @throws InvalidConfigException
126
     */
127
    protected function setMultiple(array $config): void
128 57
    {
129
        foreach ($config as $id => $definition) {
130 57
            $this->set((string)$id, $definition);
131 46
        }
132
    }
133 56
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
    private function build(string $id)
145 51
    {
146
        if (isset($this->building[$id])) {
147 51
            throw new CircularReferenceException(sprintf(
148 7
                'Circular reference to "%s" detected while building: %s',
149 7
                $id,
150
                implode(',', array_keys($this->building))
151 7
            ));
152
        }
153
154
        $this->building[$id] = 1;
155 51
        $object = $this->buildInternal($id);
156 51
        unset($this->building[$id]);
157 42
158
        return $object;
159 42
    }
160
161
    private function processDefinition($definition): void
162 43
    {
163
        if ($definition instanceof DeferredServiceProviderInterface) {
164 43
            $definition->register($this);
165 1
        }
166
    }
167 43
168
    private function validateDefinition($definition): void
169 49
    {
170
        if ($definition instanceof Reference || $definition instanceof DynamicReference) {
171 49
            return;
172 4
        }
173
174
        if (\is_string($definition)) {
175 48
            return;
176 39
        }
177
178
        if (\is_callable($definition)) {
179 17
            return;
180 5
        }
181
182
        if (\is_array($definition)) {
183 12
            return;
184 8
        }
185
186
        if (\is_object($definition)) {
187 4
            return;
188 3
        }
189
190
        throw new InvalidConfigException('Invalid definition:' . var_export($definition, true));
191 1
    }
192
193
    /**
194 51
     * @param string $id
195
     *
196 51
     * @return mixed|object
197
     * @throws InvalidConfigException
198
     * @throws NotFoundException
199
     */
200
    private function buildInternal(string $id)
201
    {
202
        if (!isset($this->definitions[$id])) {
203
            return $this->buildPrimitive($id);
204
        }
205
        $this->processDefinition($this->definitions[$id]);
206 51
        $definition = Normalizer::normalize($this->definitions[$id], $id);
207
208 51
        return $definition->resolve($this->rootContainer ?? $this);
209 37
    }
210
211 43
    /**
212 43
     * @param string $class
213
     *
214 43
     * @return mixed|object
215
     * @throws InvalidConfigException
216
     * @throws NotFoundException
217
     */
218
    private function buildPrimitive(string $class)
219
    {
220
        if (class_exists($class)) {
221
            $definition = new ArrayDefinition($class);
222
223
            return $definition->resolve($this->rootContainer ?? $this);
224 37
        }
225
226 37
        throw new NotFoundException("No definition for $class");
227 35
    }
228
229 35
    private function addProviders(array $providers): void
230
    {
231
        foreach ($providers as $provider) {
232 3
            $this->addProvider($provider);
233
        }
234
    }
235 56
236
    /**
237 56
     * Adds service provider to the container. Unless service provider is deferred
238 4
     * it would be immediately registered.
239
     *
240 55
     * @param string|array $providerDefinition
241
     *
242
     * @throws InvalidConfigException
243
     * @throws NotInstantiableException
244
     * @see ServiceProviderInterface
245
     * @see DeferredServiceProviderInterface
246
     */
247
    private function addProvider($providerDefinition): void
248
    {
249
        $provider = $this->buildProvider($providerDefinition);
250
251
        if ($provider instanceof DeferredServiceProviderInterface) {
252
            foreach ($provider->provides() as $id) {
253 4
                $this->definitions[$id] = $provider;
254
            }
255 4
        } else {
256
            $provider->register($this);
257 3
        }
258 1
    }
259 1
260
    /**
261
     * Builds service provider by definition.
262 2
     *
263
     * @param string|array $providerDefinition class name or definition of provider.
264 3
     * @return ServiceProviderInterface instance of service provider;
265
     *
266
     * @throws InvalidConfigException
267
     */
268
    private function buildProvider($providerDefinition): ServiceProviderInterface
269
    {
270
        $provider = Normalizer::normalize($providerDefinition)->resolve($this);
271
        if (!($provider instanceof ServiceProviderInterface)) {
272
            throw new InvalidConfigException(
273
                'Service provider should be an instance of ' . ServiceProviderInterface::class
274 4
            );
275
        }
276 4
277 3
        return $provider;
278
    }
279
}
280