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

Router::handleException()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
nc 2
nop 2
dl 0
loc 10
ccs 6
cts 6
cp 1
crap 2
rs 10
c 1
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
use function get_class;
15
16
final class Router
17
{
18
    /**
19
     * @throws ReflectionException
20
     */
21 79
    public static function configure(Closure $fn): void
22
    {
23 79
        $routes = new Routes();
24 79
        $bindings = new Bindings();
25 79
        $handlers = new Handlers();
26
27 79
        $params = array_map(static fn ($param) => match ((string)$param->getType()) {
28 79
            Routes::class => $routes,
29 79
            Bindings::class => $bindings,
30 79
            Handlers::class => $handlers,
31 79
            default => null,
32 79
        }, (new ReflectionFunction($fn))->getParameters());
33
34 79
        $fn(...$params);
35
36
        try {
37 78
            echo self::findRoute($routes)->run($bindings);
38 2
        } catch (Exception $exception) {
39 2
            echo self::handleException($handlers, $exception);
40
        }
41
    }
42
43 78
    private static function findRoute(Routes $routes): Route
44
    {
45 78
        foreach ($routes->getAllRoutes() as $route) {
46 77
            if ($route->requestMatches()) {
47 72
                return $route;
48
            }
49
        }
50
51 6
        return new Route('', '/', NotFound404Controller::class);
52
    }
53
54 2
    private static function handleException(Handlers $handlers, Exception $exception): string
55
    {
56 2
        $handler = $handlers->getAllHandlers()[get_class($exception)] ?? null;
57
58 2
        if ($handler === null) {
59 1
            header('HTTP/1.1 500 Internal Server Error');
60 1
            return '';
61
        }
62
63 1
        return $handler($exception);
64
    }
65
}
66