Passed
Push — main ( 50aede...a9f24b )
by Chema
01:07 queued 13s
created

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