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

Router::handleException()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 2
dl 0
loc 9
ccs 6
cts 6
cp 1
crap 2
rs 10
c 0
b 0
f 0
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