Test Failed
Push — main ( 9648cd...9515e9 )
by Fractal
02:38 queued 02:38
created

ConstraintExtractor   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 20
c 2
b 0
f 0
dl 0
loc 36
ccs 14
cts 14
cp 1
rs 10
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A extract() 0 6 2
A extractConstraints() 0 23 3
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 Symfony\Component\Validator\Constraints\All;
13
use Symfony\Component\Validator\Constraints\Collection;
14
15
#[AsService]
16
class ConstraintExtractor
17
{
18
    public function extract(string $className, array $parameters = []): ?Collection
19
    {
20
        try {
21
            return ConstraintsHelper::createCollection($this->extractConstraints($className, $parameters));
22
        } catch (\ReflectionException) {
23
            return null;
24
        }
25 15
    }
26
27
    /** @throws \ReflectionException */
28
    public function extractConstraints(string $className, array $parameters = []): array
29
    {
30 15
        $constraints = [];
31
        $reflectionClass = new \ReflectionClass($className);
32
33 15
        if ($parentClass = $reflectionClass->getParentClass()) {
34 1
            $constraints = $this->extractConstraints($parentClass->getName());
35 1
        }
36
37
        foreach ($reflectionClass->getProperties() as $property) {
38
            $propertyName = PropertyHelper::getName($property);
39
            $propertyValue = $parameters[$propertyName] ?? [];
40 15
            $propertyTypeName = PropertyHelper::getTypeName($property);
41
            $arrayTypeName = ConstraintsHelper::getArrayTypeAttribute($property)?->typeName;
42 15
43 15
            $constraints[$propertyName] = match (true) {
44 15
                ConstraintsHelper::hasArrayTypeAttribute($property) => ArrayList::collect($propertyValue)->map(fn () => new All($this->extract($arrayTypeName, $propertyValue)))->toArray(),
45
                ClassHelper::isNotBuiltinAndExists($propertyTypeName) => $this->extract($propertyTypeName, $propertyValue),
46 15
                default => ConstraintsHelper::fromProperty($property),
47 15
            };
48 15
        }
49 15
50 15
        return $constraints;
51 15
    }
52
}
53