|
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->extract($propertyName, $propertyValue), |
|
|
|
|
|
|
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
|
|
|
#[Pure] |
|
46
|
|
|
private function mapEnum(string $enumClassName, mixed $value = null): ?\BackedEnum |
|
|
|
|
|
|
47
|
|
|
{ |
|
48
|
|
|
return match (true) { |
|
49
|
|
|
is_subclass_of($enumClassName, \IntBackedEnum::class) && \is_int($value) && !empty($value) => $enumClassName::tryFrom($value), |
|
|
|
|
|
|
50
|
|
|
is_subclass_of($enumClassName, \StringBackedEnum::class) && \is_string($value) && !empty($value) => $enumClassName::tryFrom($value), |
|
|
|
|
|
|
51
|
|
|
default => null, |
|
52
|
|
|
}; |
|
53
|
|
|
} |
|
54
|
|
|
} |
|
55
|
|
|
|