Test Failed
Push — main ( ab57df...39c21d )
by Fractal
03:48
created

ParamConverterHelper   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 22
c 0
b 0
f 0
dl 0
loc 54
ccs 23
cts 23
cp 1
rs 10
wmc 7
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\RequestMapper\Attribute\RequestBody;
9
use JetBrains\PhpStorm\Immutable;
10
use JetBrains\PhpStorm\Pure;
11
12
/** @internal */
13
#[Immutable]
14
final class ParamConverterHelper
15
{
16
    private const REQUEST_POSTFIXES = ['Request', 'Dto', 'DTO'];
17
18
    private function __construct()
19
    {
20
    }
21
22 20
    public static function getAttribute(\ReflectionParameter $parameter, array $attributes): ?RequestBody
23
    {
24 20
        return $attributes[PropertyHelper::getName($parameter)]
25 13
            ?? $attributes[PropertyHelper::getTypeName($parameter)]
26 20
            ?? self::searchAttribute($parameter, $attributes);
27
    }
28
29 20
    #[Pure]
30
    public static function mapParamConverter(RequestBody $paramConverter): array
31
    {
32 20
        return [$paramConverter->argumentName ?? $paramConverter->requestClass => $paramConverter];
33
    }
34
35 20
    /** @return array<string, RequestBody> */
36
    public static function fromReflectionAttributes(\ReflectionAttribute ...$attributes): array
37 20
    {
38
        return ArrayList::collect($attributes)
39
            ->map(static fn (\ReflectionAttribute $ra): RequestBody => $ra->newInstance())
40
            ->map(static fn (RequestBody $rb): array => self::mapParamConverter($rb))
41 20
            ->reduce(array_merge(...))
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected ')' on line 41 at column 36
Loading history...
42
            ->getOrElse([])
43 20
        ;
44 20
    }
45 20
46 20
    public static function fromReflectionParameter(\ReflectionParameter $parameter): ?RequestBody
47 20
    {
48
        $parameterName = $parameter->getName();
49
        $parameterType = PropertyHelper::getTypeName($parameter);
50
51 7
        return match (true) {
52
            !$parameterType, !ClassHelper::isNameContains($parameterType, ...self::REQUEST_POSTFIXES) => null,
53 7
            default => new RequestBody(requestClass: $parameterType, argumentName: $parameterName),
54 7
        };
55
    }
56
57 7
    private static function searchAttribute(\ReflectionParameter $parameter, array $attributes): ?RequestBody
58 7
    {
59
        return ArrayList::collect($attributes)
60
            ->first(static fn (RequestBody $pc): bool => $pc->equals($parameter))
61
            ->getOrElse(self::fromReflectionParameter($parameter))
62 7
        ;
63
    }
64
}
65