Passed
Pull Request — main (#29)
by
unknown
03:12 queued 41s
created

RouteParams   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

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

3 Methods

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