Passed
Pull Request — master (#152)
by Alexander
15:01
created

Container::isTagAlias()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 0
cp 0
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\Exceptions\CircularReferenceException;
11
use Yiisoft\Factory\Exceptions\InvalidConfigException;
12
use Yiisoft\Factory\Exceptions\NotFoundException;
13
use Yiisoft\Factory\Exceptions\NotInstantiableException;
14
use Yiisoft\Factory\Definitions\Normalizer;
15
use Yiisoft\Factory\Definitions\ArrayDefinition;
16
use Yiisoft\Factory\Definitions\DefinitionResolver;
17
use Yiisoft\Injector\Injector;
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 ?CompositeContainer $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 65
     */
51
    public function __construct(
52
        array $definitions = [],
53
        array $providers = [],
54
        ContainerInterface $rootContainer = null
55 65
    ) {
56 65
        $this->delegateLookup($rootContainer);
57 63
        $this->setMultiple($definitions);
58 63
        if (!$this->has(ContainerInterface::class)) {
59
            $this->set(ContainerInterface::class, $rootContainer ?? $this);
60 63
        }
61
        $this->addProviders($providers);
62
63 62
        # Prevent circular reference to ContainerInterface
64 62
        $this->get(ContainerInterface::class);
65
    }
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 63
     */
73
    public function has($id): bool
74 63
    {
75
        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 62
     */
90
    public function get($id)
91 62
    {
92 62
        if (!isset($this->instances[$id])) {
93
            $this->instances[$id] = $this->build($id);
94
        }
95 62
96
        return $this->instances[$id];
97
    }
98
99
    /**
100
     * Delegate service lookup to another container.
101
     * @param ContainerInterface $container
102 65
     */
103
    protected function delegateLookup(?ContainerInterface $container): void
104 65
    {
105 65
        if ($container === null) {
106
            return;
107 7
        }
108 7
        if ($this->rootContainer === null) {
109
            $this->rootContainer = new CompositeContainer();
110
        }
111 7
112 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

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