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

RouteParams   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 28
c 3
b 0
f 0
dl 0
loc 55
ccs 31
cts 31
cp 1
rs 10
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getAll() 0 3 1
A getParams() 0 40 3
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