Passed
Push — main ( 55fc6d...13bcd8 )
by Chema
52s queued 13s
created

Router   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 23
dl 0
loc 48
ccs 25
cts 25
cp 1
rs 10
c 2
b 0
f 0
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A findHandler() 0 9 2
A configure() 0 20 2
A findRoute() 0 9 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gacela\Router;
6
7
use Closure;
8
use Exception;
9
use Gacela\Router\Entities\Route;
10
use Gacela\Router\Exceptions\NotFound404Exception;
11
use ReflectionException;
12
use ReflectionFunction;
13
14
use function get_class;
15
16
final class Router
17
{
18
    /**
19
     * @throws ReflectionException
20
     */
21 81
    public static function configure(Closure $fn): void
22
    {
23 81
        $routes = new Routes();
24 81
        $bindings = new Bindings();
25 81
        $handlers = new Handlers();
26
27 81
        $params = array_map(static fn ($param) => match ((string)$param->getType()) {
28 81
            Routes::class => $routes,
29 81
            Bindings::class => $bindings,
30 81
            Handlers::class => $handlers,
31 81
            default => null,
32 81
        }, (new ReflectionFunction($fn))->getParameters());
33
34 81
        $fn(...$params);
35
36
        try {
37 80
            echo self::findRoute($routes)
38 80
                ->run($bindings);
39 10
        } catch (Exception $exception) {
40 10
            echo (string) self::findHandler($handlers, $exception)($exception);
41
        }
42
    }
43
44 80
    private static function findRoute(Routes $routes): Route
45
    {
46 80
        foreach ($routes->getAllRoutes() as $route) {
47 78
            if ($route->requestMatches()) {
48 73
                return $route;
49
            }
50
        }
51
52 7
        throw new NotFound404Exception();
53
    }
54
55 10
    private static function findHandler(Handlers $handlers, Exception $exception): callable
56
    {
57 10
        $handler = $handlers->getAllHandlers()[get_class($exception)] ?? null;
58
59 10
        if ($handler === null) {
60 2
            return $handlers->getAllHandlers()[Exception::class];
61
        }
62
63 8
        return $handler;
64
    }
65
}
66