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