Passed
Pull Request — main (#7)
by
unknown
02:07
created

RouteParams::getParams()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 43
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 28
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 26
nc 6
nop 0
dl 0
loc 43
ccs 28
cts 28
cp 1
crap 5
rs 9.1928
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gacela\Router\Entities;
6
7
use ReflectionClass;
8
use ReflectionNamedType;
9
10
use function count;
11
12
final class RouteParams
13
{
14
    private array $asArray;
15
16 65
    public function __construct(
17
        private Route $route,
18
    ) {
19 65
        $this->asArray = $this->getParams();
20
    }
21
22 65
    public function asArray(): array
23
    {
24 65
        return $this->asArray;
25
    }
26
27
    /**
28
     * @psalm-suppress MixedAssignment,PossiblyNullReference
29
     */
30 65
    private function getParams(): array
31
    {
32 65
        $params = [];
33 65
        $pathParamKeys = [];
34 65
        $pathParamValues = [];
35
36 65
        preg_match($this->route->getPathPattern(), '/' . $this->route->path(), $pathParamKeys);
37 65
        preg_match($this->route->getPathPattern(), Request::fromGlobals()->path(), $pathParamValues);
38
39 65
        unset($pathParamValues[0], $pathParamKeys[0]);
40 65
        $pathParamKeys = array_map(static fn ($key) => trim($key, '{}'), $pathParamKeys);
41
42 65
        while (count($pathParamValues) !== count($pathParamKeys)) {
43 2
            array_shift($pathParamKeys);
44
        }
45
46 65
        $pathParams = array_combine($pathParamKeys, $pathParamValues);
47 65
        $actionParams = (new ReflectionClass($this->route->controller()))
48 65
            ->getMethod($this->route->action())
49 65
            ->getParameters();
50
51 65
        foreach ($actionParams as $actionParam) {
52
            /** @var string|null $paramType */
53 36
            $paramType = null;
54
55 36
            if ($actionParam->getType() && is_a($actionParam->getType(), ReflectionNamedType::class)) {
56 36
                $paramType = $actionParam->getType()->getName();
57
            }
58
59 36
            $paramName = $actionParam->getName();
60
61 36
            $value = match ($paramType) {
62 36
                'string' => $pathParams[$paramName] ?? '',
63 36
                'int' => (int)($pathParams[$paramName] ?? 0),
64 36
                'float' => (float)($pathParams[$paramName] ?? 0.0),
65 36
                'bool' => (bool)json_decode($pathParams[$paramName] ?? '0'),
66 36
                null => null,
67 36
            };
68
69 36
            $params[$paramName] = $value;
70
        }
71
72 65
        return $params;
73
    }
74
}
75