1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace FRZB\Component\RequestMapper\Extractor; |
6
|
|
|
|
7
|
|
|
use FRZB\Component\DependencyInjection\Attribute\AsService; |
8
|
|
|
use FRZB\Component\PhpDocReader\Reader\ReaderInterface as PhpDocReader; |
9
|
|
|
use FRZB\Component\RequestMapper\Helper\ClassHelper; |
10
|
|
|
use FRZB\Component\RequestMapper\Helper\PropertyHelper; |
11
|
|
|
use JetBrains\PhpStorm\Pure; |
12
|
|
|
|
13
|
|
|
#[AsService] |
14
|
|
|
class ParametersExtractor |
15
|
|
|
{ |
16
|
|
|
public function __construct( |
17
|
19 |
|
private readonly PhpDocReader $reader, |
18
|
|
|
) { |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
public function extract(string $class, array $parameters): array |
22
|
19 |
|
{ |
23
|
|
|
return [...$parameters, ...$this->mapProperties(PropertyHelper::getMapping($class, $parameters, $this->reader), $parameters)]; |
24
|
19 |
|
} |
25
|
|
|
|
26
|
|
|
private function mapProperties(array $properties, array $parameters): array |
27
|
19 |
|
{ |
28
|
|
|
$mapping = []; |
29
|
19 |
|
|
30
|
19 |
|
foreach ($properties as $propertyName => $propertyType) { |
31
|
19 |
|
$propertyValue = $parameters[$propertyName] ?? null; |
32
|
19 |
|
|
33
|
19 |
|
$mapping[$propertyName] = match (true) { |
34
|
19 |
|
\is_array($propertyType) => $this->mapPropertiesForArray($propertyValue, current($propertyType)), |
|
|
|
|
35
|
19 |
|
ClassHelper::isNotBuiltinAndExists($propertyType) => $this->extract($propertyType, $propertyValue ?? []), |
36
|
|
|
ClassHelper::isEnum($propertyType) => $this->mapEnum($propertyType, $propertyValue) ?? $propertyValue, |
37
|
19 |
|
!ClassHelper::isNotBuiltinAndExists($propertyType) => $propertyValue, |
38
|
19 |
|
default => $propertyValue, |
39
|
|
|
}; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
return $mapping; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
private function mapPropertiesForArray(array $parameters, string $propertyType): array |
46
|
|
|
{ |
47
|
|
|
$mapping = []; |
48
|
|
|
|
49
|
|
|
foreach ($parameters as $index => $params) { |
50
|
|
|
$mapping[$index] = $this->extract($propertyType, $params ?? []); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
return $mapping; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
#[Pure] |
57
|
|
|
private function mapEnum(string $enumClassName, mixed $value = null): ?\BackedEnum |
|
|
|
|
58
|
|
|
{ |
59
|
|
|
return match (true) { |
60
|
|
|
is_subclass_of($enumClassName, \IntBackedEnum::class) && \is_int($value) && !empty($value) => $enumClassName::tryFrom($value), |
|
|
|
|
61
|
|
|
is_subclass_of($enumClassName, \StringBackedEnum::class) && \is_string($value) && !empty($value) => $enumClassName::tryFrom($value), |
|
|
|
|
62
|
|
|
default => null, |
63
|
|
|
}; |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|