Passed
Pull Request — main (#13)
by
unknown
02:27
created

Router   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A handleException() 0 9 2
A configure() 0 19 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\Controllers\NotFound404Controller;
10
use Gacela\Router\Entities\Route;
11
use ReflectionException;
12
use ReflectionFunction;
13
14
final class Router
15
{
16
    /**
17
     * @throws ReflectionException
18
     */
19 79
    public static function configure(Closure $fn): void
20
    {
21 79
        $routes = new Routes();
22 79
        $bindings = new Bindings();
23 79
        $handlers = new Handlers();
24
25 79
        $params = array_map(static fn ($param) => match ((string)$param->getType()) {
26 79
            Routes::class => $routes,
27 79
            Bindings::class => $bindings,
28 79
            Handlers::class => $handlers,
29 79
            default => null,
30 79
        }, (new ReflectionFunction($fn))->getParameters());
31
32 79
        $fn(...$params);
33
34
        try {
35 78
            echo self::findRoute($routes)->run($bindings);
36 2
        } catch (Exception $exception) {
37 2
            echo self::handleException($handlers, $exception);
38
        }
39
    }
40
41 78
    private static function findRoute(Routes $routes): Route
42
    {
43 78
        foreach ($routes->getAllRoutes() as $route) {
44 77
            if ($route->requestMatches()) {
45 72
                return $route;
46
            }
47
        }
48
49 6
        return new Route('', '/', NotFound404Controller::class);
50
    }
51
52 2
    private static function handleException(Handlers $handlers, Exception $exception): string
53
    {
54 2
        $handler = $handlers->getByException($exception);
55 2
        if ($handler === null) {
56 1
            header('HTTP/1.1 500 Internal Server Error');
57 1
            return '';
58
        }
59
60 1
        return $handler($exception);
61
    }
62
}
63