Passed
Pull Request — main (#29)
by
unknown
03:12 queued 41s
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 87
    public function __construct(
17
        private Route $route,
18
    ) {
19 87
        $this->params = $this->getParams();
20
    }
21
22 85
    public function getAll(): array
23
    {
24 85
        return $this->params;
25
    }
26
27
    /**
28
     * @psalm-suppress MixedAssignment,PossiblyNullReference
29
     */
30 87
    private function getParams(): array
31
    {
32 87
        $params = [];
33 87
        $pathParamKeys = [];
34 87
        $pathParamValues = [];
35
36 87
        preg_match($this->route->getPathPattern(), '/' . $this->route->path(), $pathParamKeys);
37 87
        preg_match($this->route->getPathPattern(), Request::fromGlobals()->path(), $pathParamValues);
38
39 87
        unset($pathParamValues[0], $pathParamKeys[0]);
40 87
        $pathParamKeys = array_map(static fn ($key) => trim($key, '{}'), $pathParamKeys);
41
42 87
        while (count($pathParamValues) !== count($pathParamKeys)) {
43 2
            array_shift($pathParamKeys);
44
        }
45
46 87
        $pathParams = array_combine($pathParamKeys, $pathParamValues);
47 87
        $actionParams = (new ReflectionClass($this->route->controller()))
48 87
            ->getMethod($this->route->action())
49 87
            ->getParameters();
50
51 87
        foreach ($actionParams as $actionParam) {
52
            /** @var string|null $paramType */
53 38
            $paramType = $actionParam->getType()?->__toString();
54
55 38
            $paramName = $actionParam->getName();
56
57 38
            $value = match ($paramType) {
58 38
                'string' => $pathParams[$paramName],
59 38
                'int' => (int)$pathParams[$paramName],
60 38
                'float' => (float)$pathParams[$paramName],
61 38
                'bool' => (bool)json_decode($pathParams[$paramName]),
62 38
                null => throw UnsupportedParamTypeException::nonTyped(),
63 38
                default => throw UnsupportedParamTypeException::fromType($paramType),
64 38
            };
65
66 36
            $params[$paramName] = $value;
67
        }
68
69 85
        return $params;
70
    }
71
}
72