fractalzombie /
frzb-request-mapper
| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace FRZB\Component\RequestMapper\Extractor; |
||
| 6 | |||
| 7 | use Fp\Collections\ArrayList; |
||
| 8 | use FRZB\Component\DependencyInjection\Attribute\AsService; |
||
| 9 | use FRZB\Component\RequestMapper\Helper\ClassHelper; |
||
| 10 | use FRZB\Component\RequestMapper\Helper\ConstraintsHelper; |
||
| 11 | use FRZB\Component\RequestMapper\Helper\PropertyHelper; |
||
| 12 | use FRZB\Component\RequestMapper\TypeExtractor\TypeExtractorLocatorInterface as TypeExtractorLocator; |
||
| 13 | use Symfony\Component\Validator\Constraints\All; |
||
| 14 | use Symfony\Component\Validator\Constraints\Collection; |
||
| 15 | |||
| 16 | #[AsService] |
||
| 17 | class ConstraintExtractor |
||
| 18 | { |
||
| 19 | public function __construct( |
||
| 20 | private readonly TypeExtractorLocator $extractorLocator, |
||
| 21 | ) { |
||
| 22 | } |
||
| 23 | |||
| 24 | public function extract(string $className, array $payload = []): ?Collection |
||
| 25 | 15 | { |
|
| 26 | try { |
||
| 27 | return ConstraintsHelper::createCollection($this->extractConstraints($className, $payload)); |
||
| 28 | } catch (\ReflectionException) { |
||
| 29 | return null; |
||
| 30 | 15 | } |
|
| 31 | } |
||
| 32 | |||
| 33 | 15 | /** @throws \ReflectionException */ |
|
| 34 | 1 | public function extractConstraints(string $className, array $parameters = []): array |
|
| 35 | 1 | { |
|
| 36 | $constraints = []; |
||
| 37 | $reflectionClass = new \ReflectionClass($className); |
||
| 38 | |||
| 39 | if ($parentClass = $reflectionClass->getParentClass()) { |
||
| 40 | 15 | $constraints = $this->extractConstraints($parentClass->getName()); |
|
| 41 | } |
||
| 42 | 15 | ||
| 43 | 15 | foreach ($reflectionClass->getProperties() as $property) { |
|
| 44 | 15 | $propertyName = PropertyHelper::getName($property); |
|
| 45 | $propertyValue = $parameters[$propertyName] ?? []; |
||
| 46 | 15 | $propertyTypeName = PropertyHelper::getTypeName($property); |
|
| 47 | 15 | ||
| 48 | 15 | $constraints[$propertyName] = match (true) { |
|
| 49 | 15 | $this->extractorLocator->has($property) => ArrayList::collect($propertyValue)->map(fn () => new All($this->extract($this->extractorLocator->get($property)->extract($property), $propertyValue)))->toArray(), |
|
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 50 | 15 | ClassHelper::isNotBuiltinAndExists($propertyTypeName) => $this->extract($propertyTypeName, $propertyValue), |
|
| 51 | 15 | default => ConstraintsHelper::fromProperty($property), |
|
| 52 | 15 | }; |
|
| 53 | 15 | } |
|
| 54 | |||
| 55 | 15 | return $constraints; |
|
| 56 | 15 | } |
|
| 57 | } |
||
| 58 |