Passed
Push — master ( 7fc72e...250307 )
by Alexander
01:57
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\Definitions\Reference;
11
use Yiisoft\Factory\Exceptions\CircularReferenceException;
12
use Yiisoft\Factory\Exceptions\InvalidConfigException;
13
use Yiisoft\Factory\Exceptions\NotFoundException;
14
use Yiisoft\Factory\Exceptions\NotInstantiableException;
15
use Yiisoft\Factory\Definitions\Normalizer;
16
use Yiisoft\Factory\Definitions\ArrayDefinition;
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 ?ContainerInterface $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 62
    public function __construct(
51
        array $definitions = [],
52
        array $providers = [],
53
        ContainerInterface $rootContainer = null
54
    ) {
55 62
        $this->setMultiple($definitions);
56 60
        if (!$this->has(ContainerInterface::class)) {
57 60
            $this->set(ContainerInterface::class, $rootContainer ?? $this);
58
        }
59 60
        $this->addProviders($providers);
60 59
        if ($rootContainer !== null) {
61 7
            $this->delegateLookup($rootContainer);
62
        }
63
        # Prevent circular reference to ContainerInterface
64 59
        $this->get(ContainerInterface::class);
65 59
    }
66
67
    /**
68
     * Returns a value indicating whether the container has the definition of the specified name.
69
     * @param string $id class name, interface name or alias name
70
     * @return bool whether the container is able to provide instance of class specified.
71
     * @see set()
72
     */
73 60
    public function has($id): bool
74
    {
75 60
        return isset($this->definitions[$id]) || class_exists($id);
76
    }
77
78
    /**
79
     * Returns an instance by either interface name or alias.
80
     *
81
     * Same instance of the class will be returned each time this method is called.
82
     *
83
     * @param string $id The interface or an alias name that was previously registered.
84
     * @return object An instance of the requested interface.
85
     * @throws CircularReferenceException
86
     * @throws InvalidConfigException
87
     * @throws NotFoundException
88
     * @throws NotInstantiableException
89
     */
90 59
    public function get($id)
91
    {
92 59
        if (!isset($this->instances[$id])) {
93 59
            $this->instances[$id] = $this->build($id);
94
        }
95
96 59
        return $this->instances[$id];
97
    }
98
99
    /**
100
     * Delegate service lookup to another container.
101
     * @param ContainerInterface $container
102
     */
103 7
    protected function delegateLookup(ContainerInterface $container): void
104
    {
105 7
        if ($this->rootContainer === null) {
106 7
            $this->rootContainer = new CompositeContainer();
107
        }
108
109 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

109
        $this->rootContainer->/** @scrutinizer ignore-call */ 
110
                              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

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