Passed
Pull Request — master (#44)
by Sergei
02:08
created

ArrayDefinition::resolve()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 32
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 16
nc 5
nop 1
dl 0
loc 32
ccs 17
cts 17
cp 1
crap 5
rs 9.4222
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Definitions;
6
7
use InvalidArgumentException;
8
use Psr\Container\ContainerInterface;
9
use ReflectionMethod;
10
use Yiisoft\Definitions\Contract\DefinitionInterface;
11
use Yiisoft\Definitions\Exception\InvalidConfigException;
12
use Yiisoft\Definitions\Helpers\DefinitionExtractor;
13
use Yiisoft\Definitions\Helpers\DefinitionResolver;
14
15
use function array_key_exists;
16
use function call_user_func_array;
17
use function count;
18
use function is_string;
19
20
/**
21
 * Builds an object by array config.
22
 *
23
 * @psalm-type MethodOrPropertyItem = array{0:string,1:string,2:mixed}
24
 * @psalm-type ArrayDefinitionConfig = array{class:class-string,'__construct()'?:array}&array<string, mixed>
25
 */
26
final class ArrayDefinition implements DefinitionInterface
27
{
28
    public const CLASS_NAME = 'class';
29
    public const CONSTRUCTOR = '__construct()';
30
31
    public const TYPE_PROPERTY = 'property';
32
    public const TYPE_METHOD = 'method';
33
34
    /**
35
     * @psalm-var class-string
36
     */
37
    private string $class;
38
    private array $constructorArguments;
39
    /**
40
      * Container used to resolve references.
41
      */
42
    private ?ContainerInterface $referenceContainer = null;
43
44
    /**
45
     * @psalm-var array<string, MethodOrPropertyItem>
46
     */
47
    private array $methodsAndProperties;
48
49
    /**
50
     * @psalm-param class-string $class
51
     * @psalm-param array<string, MethodOrPropertyItem> $methodsAndProperties
52
     */
53 40
    private function __construct(string $class, array $constructorArguments, array $methodsAndProperties)
54
    {
55 40
        $this->class = $class;
56 40
        $this->constructorArguments = $constructorArguments;
57 40
        $this->methodsAndProperties = $methodsAndProperties;
58
    }
59
60
    /**
61
     * @param ContainerInterface|null $referenceContainer Container to resolve references with.
62
     */
63 1
    public function withReferenceContainer(?ContainerInterface $referenceContainer): self
64
    {
65 1
        $new = clone $this;
66 1
        $new->referenceContainer = $referenceContainer;
67 1
        return $new;
68
    }
69
70
    /**
71
     * Create ArrayDefinition from array config.
72
     *
73
     * @psalm-param ArrayDefinitionConfig $config
74
     */
75 38
    public static function fromConfig(array $config): self
76
    {
77 38
        return new self(
78 38
            $config[self::CLASS_NAME],
79 38
            $config[self::CONSTRUCTOR] ?? [],
80 38
            self::getMethodsAndPropertiesFromConfig($config)
81
        );
82
    }
83
84
    /**
85
     * @psalm-param class-string $class
86
     * @psalm-param array<string, MethodOrPropertyItem> $methodsAndProperties
87
     */
88 2
    public static function fromPreparedData(string $class, array $constructorArguments = [], array $methodsAndProperties = []): self
89
    {
90 2
        return new self($class, $constructorArguments, $methodsAndProperties);
91
    }
92
93
    /**
94
     * @psalm-param array<string, mixed> $config
95
     *
96
     * @psalm-return array<string, MethodOrPropertyItem>
97
     */
98 38
    private static function getMethodsAndPropertiesFromConfig(array $config): array
99
    {
100 38
        $methodsAndProperties = [];
101
102
        /** @var mixed $value */
103 38
        foreach ($config as $key => $value) {
104 38
            if ($key === self::CONSTRUCTOR) {
105 12
                continue;
106
            }
107
108 38
            if (count($methodArray = explode('()', $key, 2)) === 2) {
109 21
                $methodsAndProperties[$key] = [self::TYPE_METHOD, $methodArray[0], $value];
110 38
            } elseif (count($propertyArray = explode('$', $key)) === 2) {
111 3
                $methodsAndProperties[$key] = [self::TYPE_PROPERTY, $propertyArray[1], $value];
112
            }
113
        }
114
115 38
        return $methodsAndProperties;
116
    }
117
118
    /**
119
     * @psalm-return class-string
120
     */
121 3
    public function getClass(): string
122
    {
123 3
        return $this->class;
124
    }
125
126 39
    public function getConstructorArguments(): array
127
    {
128 39
        return $this->constructorArguments;
129
    }
130
131
    /**
132
     * @psalm-return array<string, MethodOrPropertyItem>
133
     */
134 37
    public function getMethodsAndProperties(): array
135
    {
136 37
        return $this->methodsAndProperties;
137
    }
138
139 36
    public function resolve(ContainerInterface $container): object
140
    {
141 36
        $resolvedConstructorArguments = $this->resolveFunctionArguments(
142
            $container,
143 36
            DefinitionExtractor::fromClassName($this->class),
144 36
            $this->getConstructorArguments()
145
        );
146
147
        /** @psalm-suppress MixedMethodCall */
148 34
        $object = new ($this->class)(...$resolvedConstructorArguments);
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected '(' on line 148 at column 22
Loading history...
149
150 34
        foreach ($this->getMethodsAndProperties() as $item) {
151
            /** @var mixed $value */
152 22
            [$type, $name, $value] = $item;
153 22
            if ($type === self::TYPE_METHOD) {
154
                /** @var array $value */
155 20
                $resolvedMethodArguments = $this->resolveFunctionArguments(
156
                    $container,
157 20
                    DefinitionExtractor::fromFunction(new ReflectionMethod($object, $name)),
158
                    $value,
159
                );
160
                /** @var mixed $setter */
161 18
                $setter = call_user_func_array([$object, $name], $resolvedMethodArguments);
162 18
                if ($setter instanceof $object) {
163
                    /** @var object $object */
164 18
                    $object = $setter;
165
                }
166 2
            } elseif ($type === self::TYPE_PROPERTY) {
167 2
                $object->$name = DefinitionResolver::resolve($container, $this->referenceContainer, $value);
168
            }
169
        }
170
171 32
        return $object;
172
    }
173
174
    /**
175
     * @param array<string,ParameterDefinition> $dependencies
176
     *
177
     * @psalm-return list<mixed>
178
     */
179 36
    private function resolveFunctionArguments(
180
        ContainerInterface $container,
181
        array $dependencies,
182
        array $arguments
183
    ): array {
184 36
        $this->injectArguments($dependencies, $arguments);
185 34
        $resolvedArguments = DefinitionResolver::resolveArray($container, $this->referenceContainer, $dependencies);
186 34
        return array_values($resolvedArguments);
187
    }
188
189
    /**
190
     * @psalm-param array<string, ParameterDefinition> $dependencies
191
     * @psalm-param-out array<array-key, Yiisoft\Definitions\ParameterDefinition|mixed> $dependencies
192
     *
193
     * @throws InvalidConfigException
194
     */
195 36
    private function injectArguments(array &$dependencies, array $arguments): void
196
    {
197 36
        $isIntegerIndexed = $this->isIntegerIndexed($arguments);
198 35
        $dependencyIndex = 0;
199 35
        $usedArguments = [];
200 35
        $variadicKey = null;
201 35
        foreach ($dependencies as $key => &$value) {
202 34
            if ($value->isVariadic()) {
203 27
                $variadicKey = $key;
204
            }
205 34
            $index = $isIntegerIndexed ? $dependencyIndex : $key;
206 34
            if (array_key_exists($index, $arguments)) {
207 26
                $value = DefinitionResolver::ensureResolvable($arguments[$index]);
208 26
                $usedArguments[$index] = 1;
209
            }
210 34
            $dependencyIndex++;
211
        }
212 35
        unset($value);
213 35
        if ($variadicKey !== null) {
214 27
            if (!$isIntegerIndexed && isset($arguments[$variadicKey])) {
215 5
                if (is_array($arguments[$variadicKey])) {
216 3
                    unset($dependencies[$variadicKey]);
217 3
                    $dependencies += $arguments[$variadicKey];
218 3
                    return;
219
                }
220
221 2
                throw new InvalidArgumentException(sprintf('Named argument for a variadic parameter should be an array, "%s" given.', gettype($arguments[$variadicKey])));
222
            }
223
224
            /** @var mixed $value */
225 22
            foreach ($arguments as $index => $value) {
226 10
                if (!isset($usedArguments[$index])) {
227 2
                    $dependencies[$index] = DefinitionResolver::ensureResolvable($value);
228
                }
229
            }
230
        }
231
    }
232
233
    /**
234
     * @throws InvalidConfigException
235
     */
236 36
    private function isIntegerIndexed(array $arguments): bool
237
    {
238 36
        $hasStringIndex = false;
239 36
        $hasIntegerIndex = false;
240
241 36
        foreach ($arguments as $index => $_argument) {
242 28
            if (is_string($index)) {
243 13
                $hasStringIndex = true;
244 13
                if ($hasIntegerIndex) {
245 13
                    break;
246
                }
247
            } else {
248 17
                $hasIntegerIndex = true;
249 17
                if ($hasStringIndex) {
250 1
                    break;
251
                }
252
            }
253
        }
254 36
        if ($hasIntegerIndex && $hasStringIndex) {
255 2
            throw new InvalidConfigException(
256
                'Arguments indexed both by name and by position are not allowed in the same array.'
257
            );
258
        }
259
260 35
        return $hasIntegerIndex;
261
    }
262
263
    /**
264
     * Create a new definition that is merged from this definition and another definition.
265
     *
266
     * @param ArrayDefinition $other Definition to merge with.
267
     *
268
     * @return self New definition that is merged from this definition and another definition.
269
     */
270 2
    public function merge(self $other): self
271
    {
272 2
        $new = clone $this;
273 2
        $new->class = $other->class;
274 2
        $new->constructorArguments = $this->mergeArguments($this->constructorArguments, $other->constructorArguments);
275
276 2
        $methodsAndProperties = $this->methodsAndProperties;
277 2
        foreach ($other->methodsAndProperties as $key => $item) {
278 1
            if ($item[0] === self::TYPE_PROPERTY) {
279 1
                $methodsAndProperties[$key] = $item;
280 1
            } elseif ($item[0] === self::TYPE_METHOD) {
281
                /** @psalm-suppress MixedArgument, MixedAssignment */
282 1
                $arguments = isset($methodsAndProperties[$key])
283 1
                    ? $this->mergeArguments($methodsAndProperties[$key][2], $item[2])
284 1
                    : $item[2];
285 1
                $methodsAndProperties[$key] = [$item[0], $item[1], $arguments];
286
            }
287
        }
288 2
        $new->methodsAndProperties = $methodsAndProperties;
289
290 2
        return $new;
291
    }
292
293 2
    private function mergeArguments(array $selfArguments, array $otherArguments): array
294
    {
295
        /** @var mixed $argument */
296 2
        foreach ($otherArguments as $name => $argument) {
297
            /** @var mixed */
298 1
            $selfArguments[$name] = $argument;
299
        }
300
301 2
        return $selfArguments;
302
    }
303
}
304