Passed
Push — master ( 3214f6...7fc72e )
by Alexander
11:48 queued 09:43
created

Container::__construct()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

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

107
        $this->rootContainer->/** @scrutinizer ignore-call */ 
108
                              attach($container);
Loading history...
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

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