1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace FRZB\Component\RequestMapper\Helper; |
6
|
|
|
|
7
|
|
|
use FRZB\Component\RequestMapper\Attribute\ParamConverter; |
8
|
|
|
use JetBrains\PhpStorm\Pure; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* @internal |
12
|
|
|
*/ |
13
|
|
|
final class ParamConverterHelper |
14
|
|
|
{ |
15
|
|
|
private const REQUEST_POSTFIXES = ['Request', 'Dto', 'DTO']; |
16
|
|
|
|
17
|
|
|
public static function getAttribute(\ReflectionParameter $parameter, array $attributes): ?ParamConverter |
18
|
|
|
{ |
19
|
|
|
return $attributes[$parameter->getName()] |
20
|
|
|
?? $attributes[$parameter->getType()?->getName()] |
|
|
|
|
21
|
|
|
?? self::searchAttribute($parameter, $attributes); |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
#[Pure] |
25
|
|
|
public static function mapParamConverter(ParamConverter $paramConverter): array |
26
|
|
|
{ |
27
|
|
|
return [$paramConverter->getParameterName() ?? $paramConverter->getParameterClass() => $paramConverter]; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** @noinspection PhpIncompatibleReturnTypeInspection */ |
31
|
|
|
public static function fromReflectionAttribute(\ReflectionAttribute $attribute): ParamConverter |
32
|
|
|
{ |
33
|
|
|
return $attribute->newInstance(); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** @return array<string, ParamConverter> */ |
37
|
|
|
public static function fromReflectionAttributes(\ReflectionAttribute ...$attributes): array |
38
|
|
|
{ |
39
|
|
|
$mapReflection = static fn (\ReflectionAttribute $ra): ParamConverter => self::fromReflectionAttribute($ra); |
40
|
|
|
$mapAttributes = static fn (ParamConverter $pc): array => self::mapParamConverter($pc); |
41
|
|
|
|
42
|
|
|
return array_merge(...array_map($mapAttributes, array_map($mapReflection, $attributes))); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
public static function fromReflectionParameter(\ReflectionParameter $parameter): ?ParamConverter |
46
|
|
|
{ |
47
|
|
|
return match (true) { |
48
|
|
|
!$parameter->getType()?->getName(), !ClassHelper::isNameContains($parameter->getType()?->getName(), ...self::REQUEST_POSTFIXES) => null, |
49
|
|
|
default => new ParamConverter(parameterClass: $parameter->getType()?->getName(), parameterName: $parameter->getName()), |
50
|
|
|
}; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
private static function searchAttribute(\ReflectionParameter $parameter, array $attributes): ?ParamConverter |
54
|
|
|
{ |
55
|
|
|
$filteredAttributes = array_filter($attributes, static fn (ParamConverter $pc): bool => $pc->equals($parameter)); |
56
|
|
|
|
57
|
|
|
return current($filteredAttributes) ?: self::fromReflectionParameter($parameter); |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|