Passed
Push — main ( a74a35...8a07cd )
by Fractal
03:04
created

PropertyHelper::getName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace FRZB\Component\RequestMapper\Helper;
6
7
use Fp\Collections\ArrayList;
8
use FRZB\Component\PhpDocReader\Exception\ReaderException;
9
use FRZB\Component\PhpDocReader\Reader\ReaderInterface as PhpDocReader;
10
use JetBrains\PhpStorm\Immutable;
11
12
/** @internal */
13
#[Immutable]
14
final class PropertyHelper
15
{
16
    private function __construct()
17
    {
18
    }
19
20 19
    public static function getMapping(string $className, mixed $value, PhpDocReader $reader): array
21
    {
22
        try {
23 19
            $properties = ArrayList::collect((new \ReflectionClass($className))->getProperties());
24
        } catch (\ReflectionException) {
25
            return [];
26
        }
27
28
        return $properties
29 19
            ->map(static fn (\ReflectionProperty $p) => match (true) {
30 19
                ConstraintsHelper::hasArrayTypeAttribute($p) => [self::getName($p) => ArrayList::range(0, \count($value))->map(fn () => self::getTypeFromAttribute($p))->toArray()],
31 19
                ConstraintsHelper::hasArrayDocBlock($p, $reader) => [self::getName($p) => ArrayList::range(0, \count($value))->map(fn () => self::getTypeFromDocBlock($p, $reader))->toArray()],
32 19
                !ConstraintsHelper::hasArrayTypeAttribute($p) => [self::getName($p) => (string) $p->getType()],
33
                !ConstraintsHelper::hasArrayDocBlock($p, $reader) => [self::getName($p) => (string) $p->getType()],
34 19
                default => [SerializerHelper::getSerializedNameAttribute($p)->getSerializedName() => []],
35
            })
36 19
            ->reduce(static fn (array $prev, array $next) => [...$prev, ...$next])
37 19
            ->getOrElse([])
38
        ;
39
    }
40
41
    public static function getTypeFromDocBlock(\ReflectionProperty $property, PhpDocReader $reader): ?string
42
    {
43
        try {
44
            return $reader->getPropertyClass($property);
45
        } catch (ReaderException) {
46
            return null;
47
        }
48
    }
49
50
    public static function getTypeFromAttribute(\ReflectionProperty $property): ?string
51
    {
52
        return ConstraintsHelper::getArrayTypeAttribute($property)?->typeName;
53
    }
54
55 19
    public static function getName(\ReflectionProperty $property): string
56
    {
57 19
        return SerializerHelper::getSerializedNameAttribute($property)->getSerializedName();
58
    }
59
}
60