Passed
Pull Request — master (#152)
by Andrii
13:25
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;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Factory\Definitions\DefinitionResolver was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
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
    public function __construct(
51 57
        array $definitions = [],
52
        array $providers = [],
53
        ContainerInterface $rootContainer = null
54
    ) {
55
        $this->setMultiple($definitions);
56 57
        if (!$this->has(ContainerInterface::class)) {
57 55
            $this->set(ContainerInterface::class, $rootContainer ?? $this);
58 54
        }
59 5
        $this->addProviders($providers);
60
        if ($rootContainer !== null) {
61 54
            $this->delegateLookup($rootContainer);
62
        }
63
    }
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 24
     * @see set()
70
     */
71 24
    public function has($id): bool
72
    {
73
        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 50
     * @throws NotInstantiableException
87
     */
88 50
    public function get($id)
89 50
    {
90
        if (!isset($this->instances[$id])) {
91
            $this->instances[$id] = $this->build($id);
92 41
        }
93
94
        return $this->instances[$id];
95
    }
96
97
    /**
98
     * Delegate service lookup to another container.
99 5
     * @param ContainerInterface $container
100
     */
101 5
    protected function delegateLookup(ContainerInterface $container): void
102 5
    {
103
        if ($this->rootContainer === null) {
104
            $this->rootContainer = new CompositeContainer();
105 5
        }
106 5
107
        $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
    }
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 48
     * @see `Normalizer::normalize()`
116
     */
117 48
    protected function set(string $id, $definition): void
118 47
    {
119 47
        Normalizer::validate($definition);
120 47
        $this->instances[$id] = null;
121
        $this->definitions[$id] = $definition;
122
    }
123
124
    /**
125
     * Sets multiple definitions at once.
126
     * @param array $config definitions indexed by their ids
127 57
     * @throws InvalidConfigException
128
     */
129 57
    protected function setMultiple(array $config): void
130 46
    {
131 1
        foreach ($config as $id => $definition) {
132
            if (!is_string($id)) {
133 45
                throw new InvalidConfigException('Key must be a string');
134
            }
135 55
            $this->set((string)$id, $definition);
136
        }
137
    }
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 50
     * @internal
148
     */
149 50
    private function build(string $id)
150 7
    {
151 7
        if (isset($this->building[$id])) {
152
            throw new CircularReferenceException(sprintf(
153 7
                'Circular reference to "%s" detected while building: %s',
154
                $id,
155
                implode(',', array_keys($this->building))
156
            ));
157 50
        }
158 50
159 41
        $this->building[$id] = 1;
160
        $object = $this->buildInternal($id);
161 41
        unset($this->building[$id]);
162
163
        return $object;
164 43
    }
165
166 43
    private function processDefinition($definition): void
167 1
    {
168
        if ($definition instanceof DeferredServiceProviderInterface) {
169 43
            $definition->register($this);
170
        }
171 48
    }
172
173 48
    /**
174 3
     * @param string $id
175
     *
176
     * @return mixed|object
177 47
     * @throws InvalidConfigException
178 38
     * @throws NotFoundException
179
     */
180
    private function buildInternal(string $id)
181 17
    {
182 5
        if (!isset($this->definitions[$id])) {
183
            return $this->buildPrimitive($id);
184
        }
185 12
        $this->processDefinition($this->definitions[$id]);
186 8
        if ($this->isTagAlias($id)) {
187
            return DefinitionResolver::resolveArray($this, $this->definitions[$id]);
188
        }
189 4
        $definition = Normalizer::normalize($this->definitions[$id], $id);
190 3
191
        return $definition->resolve($this->rootContainer ?? $this);
192
    }
193 1
194
    private function isTagAlias(string $id): bool
195
    {
196
        return strpos($id, 'tag@') === 0;
197
    }
198
199
    /**
200
     * @param string $class
201
     *
202
     * @return mixed|object
203 50
     * @throws InvalidConfigException
204
     * @throws NotFoundException
205 50
     */
206 35
    private function buildPrimitive(string $class)
207
    {
208 43
        if (class_exists($class)) {
209 43
            $definition = new ArrayDefinition($class);
210
211 43
            return $definition->resolve($this->rootContainer ?? $this);
212
        }
213
214
        throw new NotFoundException("No definition for $class");
215
    }
216
217
    private function addProviders(array $providers): void
218
    {
219
        foreach ($providers as $provider) {
220
            $this->addProvider($provider);
221 35
        }
222
    }
223 35
224 33
    /**
225
     * Adds service provider to the container. Unless service provider is deferred
226 33
     * it would be immediately registered.
227
     *
228
     * @param string|array $providerDefinition
229 3
     *
230
     * @throws InvalidConfigException
231
     * @throws NotInstantiableException
232 55
     * @see ServiceProviderInterface
233
     * @see DeferredServiceProviderInterface
234 55
     */
235 4
    private function addProvider($providerDefinition): void
236
    {
237 54
        $provider = $this->buildProvider($providerDefinition);
238
239
        if ($provider instanceof DeferredServiceProviderInterface) {
240
            foreach ($provider->provides() as $id) {
241
                $this->definitions[$id] = $provider;
242
            }
243
        } else {
244
            $provider->register($this);
245
        }
246
    }
247
248
    /**
249
     * Builds service provider by definition.
250 4
     *
251
     * @param string|array $providerDefinition class name or definition of provider.
252 4
     * @return ServiceProviderInterface instance of service provider;
253
     *
254 3
     * @throws InvalidConfigException
255 1
     */
256 1
    private function buildProvider($providerDefinition): ServiceProviderInterface
257
    {
258
        $provider = Normalizer::normalize($providerDefinition)->resolve($this);
259 2
        if (!($provider instanceof ServiceProviderInterface)) {
260
            throw new InvalidConfigException(
261 3
                'Service provider should be an instance of ' . ServiceProviderInterface::class
262
            );
263
        }
264
265
        return $provider;
266
    }
267
}
268