Passed
Push — main ( ee7b7b...414146 )
by Fractal
02:40
created

getDiscriminatorMapAttribute()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 11
ccs 7
cts 7
cp 1
crap 3
rs 10
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\RequestMapper\Exception\ClassExtractorException;
9
use Symfony\Component\Serializer\Annotation\DiscriminatorMap;
10
11
#[AsService]
12
class DiscriminatorMapExtractor
13
{
14
    /** @throws ClassExtractorException */
15 17
    public function extract(string $class, array $parameters): string
16
    {
17 17
        if ($discriminatorMap = $this->getDiscriminatorMapAttribute($class)) {
18 3
            $property = $discriminatorMap->getTypeProperty();
19 3
            $mapping = $discriminatorMap->getMapping();
20 3
            $parameter = $parameters[$property] ?? throw ClassExtractorException::fromDiscriminatorMapWhenParameterIsNull($discriminatorMap);
21 3
            $class = $mapping[$parameter] ?? throw ClassExtractorException::fromDiscriminatorMapWhenParameterInvalid($discriminatorMap);
22
        }
23
24 16
        return $class;
25
    }
26
27 17
    private function getDiscriminatorMapAttribute(string $class): ?DiscriminatorMap
28
    {
29
        try {
30 17
            $discriminators = array_map(
31 17
                static fn (\ReflectionAttribute $attribute) => $attribute->newInstance(),
32 17
                (new \ReflectionClass($class))->getAttributes(DiscriminatorMap::class),
33
            );
34
35 16
            return current($discriminators) ?: null;
36 1
        } catch (\ReflectionException) {
37 1
            return null;
38
        }
39
    }
40
}
41