-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInputQuery.php
More file actions
375 lines (315 loc) · 11.4 KB
/
InputQuery.php
File metadata and controls
375 lines (315 loc) · 11.4 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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
<?php
declare(strict_types=1);
namespace Ray\InputQuery;
use ArrayObject;
use InvalidArgumentException;
use Override;
use Ray\Di\Di\Named;
use Ray\Di\Di\Qualifier;
use Ray\Di\Exception\Unbound;
use Ray\Di\InjectorInterface;
use Ray\InputQuery\Attribute\Input;
use ReflectionAttribute;
use ReflectionClass;
use ReflectionMethod;
use ReflectionNamedType;
use ReflectionParameter;
use function array_key_exists;
use function assert;
use function class_exists;
use function gettype;
use function is_array;
use function is_bool;
use function is_float;
use function is_int;
use function is_numeric;
use function is_scalar;
use function is_string;
use function is_subclass_of;
use function lcfirst;
use function sprintf;
use function str_replace;
use function str_starts_with;
use function strlen;
use function strtolower;
use function substr;
use function ucwords;
/**
* @template T of object
* @implements InputQueryInterface<T>
*/
final class InputQuery implements InputQueryInterface
{
public function __construct(
private InjectorInterface $injector,
) {
}
/**
* {@inheritDoc}
*/
#[Override]
public function getArguments(ReflectionMethod $method, array $query): array
{
$args = [];
foreach ($method->getParameters() as $param) {
/** @psalm-suppress MixedAssignment */
$args[] = $this->resolveParameter($param, $query);
}
return $args;
}
/**
* @param class-string<T> $class
* @param array<string, mixed> $query
*
* @return T
*/
#[Override]
public function create(string $class, array $query): object
{
$reflection = new ReflectionClass($class);
$constructor = $reflection->getConstructor();
if (! $constructor) {
return $reflection->newInstance();
}
$args = $this->getArguments($constructor, $query);
return $reflection->newInstanceArgs($args);
}
/** @param array<string, mixed> $query */
private function resolveParameter(ReflectionParameter $param, array $query): mixed
{
$inputAttributes = $param->getAttributes(Input::class);
$hasInputAttribute = ! empty($inputAttributes);
if (! $hasInputAttribute) {
// No #[Input] attribute - get from DI
return $this->resolveFromDI($param);
}
return $this->resolveInputParameter($param, $query, $inputAttributes);
}
/**
* @param array<string, mixed> $query
* @param array<ReflectionAttribute<Input>> $inputAttributes
*/
private function resolveInputParameter(ReflectionParameter $param, array $query, array $inputAttributes): mixed
{
$type = $param->getType();
$paramName = $param->getName();
if (! $type instanceof ReflectionNamedType) {
return $query[$paramName] ?? $this->getDefaultValue($param);
}
if ($type->isBuiltin()) {
return $this->resolveBuiltinType($param, $query, $inputAttributes, $type);
}
return $this->resolveObjectType($param, $query, $inputAttributes, $type);
}
/**
* @param array<string, mixed> $query
* @param array<ReflectionAttribute<Input>> $inputAttributes
*/
private function resolveBuiltinType(ReflectionParameter $param, array $query, array $inputAttributes, ReflectionNamedType $type): mixed
{
$paramName = $param->getName();
if ($type->getName() === 'array') {
$inputAttribute = $inputAttributes[0]->newInstance();
if ($inputAttribute->item !== null) {
assert(class_exists($inputAttribute->item));
$itemClass = $inputAttribute->item;
/** @var class-string<T> $itemClass */
return $this->createArrayOfInputs($paramName, $query, $itemClass);
}
}
// Scalar type with #[Input]
/** @psalm-suppress MixedAssignment $value */
$value = $query[$paramName] ?? $this->getDefaultValue($param);
return $this->convertScalar($value, $type);
}
/**
* @param array<string, mixed> $query
* @param array<ReflectionAttribute<Input>> $inputAttributes
*/
private function resolveObjectType(ReflectionParameter $param, array $query, array $inputAttributes, ReflectionNamedType $type): mixed
{
$paramName = $param->getName();
$className = $type->getName();
// Check for ArrayObject types with item specification
$arrayObjectResult = $this->resolveArrayObjectType($paramName, $query, $inputAttributes, $className);
if ($arrayObjectResult !== null) {
return $arrayObjectResult;
}
// Regular object type with #[Input] - create nested
$nestedQuery = $this->extractNestedQuery($paramName, $query);
// If no nested keys found, try using the entire query
if (empty($nestedQuery)) {
$nestedQuery = $query;
}
assert(class_exists($className));
/** @var class-string<T> $className */
return $this->create($className, $nestedQuery);
}
/**
* @param array<string, mixed> $query
* @param array<ReflectionAttribute<Input>> $inputAttributes
*/
private function resolveArrayObjectType(string $paramName, array $query, array $inputAttributes, string $className): mixed
{
$isArrayObjectSubclass = class_exists($className) && is_subclass_of($className, ArrayObject::class);
$isArrayObject = $className === ArrayObject::class;
if (! $isArrayObjectSubclass && ! $isArrayObject) {
return null;
}
$inputAttribute = $inputAttributes[0]->newInstance();
if ($inputAttribute->item === null) {
return null;
}
assert(class_exists($inputAttribute->item));
/** @var class-string<T> $itemClass */
$itemClass = $inputAttribute->item;
$array = $this->createArrayOfInputs($paramName, $query, $itemClass);
if ($isArrayObject) {
return new ArrayObject($array);
}
assert(class_exists($className));
/** @var class-string $className */
$reflectionClass = new ReflectionClass($className);
return $reflectionClass->newInstance($array);
}
private function resolveFromDI(ReflectionParameter $param): mixed
{
$interface = $this->getInterface($param);
$qualifier = $this->getQualifier($param);
try {
return $this->injector->getInstance($interface, $qualifier);
} catch (Unbound $e) {
// If the type is not bound, we need to handle it
// If it's a scalar type, return default value
if ($param->isDefaultValueAvailable()) {
return $param->getDefaultValue();
}
// If it's an object type, throw an exception
throw new InvalidArgumentException(sprintf(
'Parameter "%s" of type "%s:%s" is not bound in the injector.',
$param->getName(),
$interface,
$qualifier,
), 0, $e);
}
}
/** @return class-string|'' */
private function getInterface(ReflectionParameter $param): string
{
$type = $param->getType();
if ($type === null || ! $type instanceof ReflectionNamedType || $type->isBuiltin()) {
return '';
}
$class = $type->getName();
assert(class_exists($class));
return $class;
}
private function getQualifier(ReflectionParameter $param): string
{
$maybeAttrs = $param->getAttributes();
foreach ($maybeAttrs as $maybeAttr) {
$attr = $maybeAttr->newInstance();
if ($attr instanceof Named) {
// If the attribute is Named, return its value
return $attr->value;
}
$maybeQualifier = (new ReflectionClass($attr))->getAttributes(Qualifier::class);
$isQualifier = ! empty($maybeQualifier);
if ($isQualifier) {
// If the attribute is Qualifier, return its value
return $attr::class;
}
}
return '';
}
private function getDefaultValue(ReflectionParameter $param): mixed
{
if ($param->isDefaultValueAvailable()) {
return $param->getDefaultValue();
}
// Required parameter without default value
throw new InvalidArgumentException(sprintf(
'Required parameter "%s" is missing and has no default value',
$param->getName(),
));
}
private function convertScalar(mixed $value, ReflectionNamedType $type): mixed
{
if ($value === null) {
return null;
}
return match ($type->getName()) {
'string' => is_string($value) ? $value : (is_scalar($value) ? (string) $value : ''),
'int' => is_int($value) ? $value : (is_numeric($value) ? (int) $value : 0),
'float' => is_float($value) ? $value : (is_numeric($value) ? (float) $value : 0.0),
'bool' => is_bool($value) ? $value : (bool) $value,
default => $value
};
}
/**
* @param array<string, mixed> $query
*
* @return array<string, mixed>
*/
private function extractNestedQuery(string $paramName, array $query): array
{
$prefix = $this->toCamelCase($paramName);
$nestedQuery = [];
/** @psalm-suppress MixedAssignment */
foreach ($query as $key => $value) {
$normalizedKey = $this->toCamelCase($key);
if (str_starts_with($normalizedKey, $prefix)) {
$nestedKey = substr($normalizedKey, strlen($prefix));
$nestedKey = lcfirst($nestedKey);
if ($nestedKey !== '') {
/** @psalm-suppress MixedAssignment */
$nestedQuery[$nestedKey] = $value;
}
}
}
return $nestedQuery;
}
private function toCamelCase(string $string): string
{
// Convert snake_case and kebab-case to camelCase
$string = str_replace(['-', '_'], ' ', strtolower($string));
$string = ucwords($string);
$string = str_replace(' ', '', $string);
return lcfirst($string);
}
/**
* @param array<string, mixed> $query
* @param class-string<T> $itemClass
*
* @return array<array-key, T>
*/
private function createArrayOfInputs(string $paramName, array $query, string $itemClass): array
{
if (! array_key_exists($paramName, $query)) {
return [];
}
/** @var mixed $arrayData */
$arrayData = $query[$paramName];
if (! is_array($arrayData)) {
return [];
}
$result = [];
/** @var mixed $itemData */
foreach ($arrayData as $key => $itemData) {
if (! is_array($itemData)) {
throw new InvalidArgumentException(
sprintf(
'Expected array for item at key "%s", got %s.',
$key,
gettype($itemData),
),
);
}
// Query parameters from HTTP requests have string keys
/** @psalm-var array<string, mixed> $itemData */
/** @phpstan-var array<string, mixed> $itemData */
$result[$key] = $this->create($itemClass, $itemData);
}
return $result;
}
}