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

ConstraintExtractor::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 0
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
ccs 1
cts 1
cp 1
crap 1
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