|
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 is_string; |
|
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
|
78 |
|
$route = self::findRoute($routes); |
|
37
|
|
|
|
|
38
|
|
|
try { |
|
39
|
78 |
|
echo $route->run($bindings); |
|
40
|
2 |
|
} catch (Exception $exception) { |
|
41
|
2 |
|
self::handleException($handlers, $exception); |
|
42
|
|
|
} |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
78 |
|
private static function findRoute(Routes $routes): Route |
|
46
|
|
|
{ |
|
47
|
78 |
|
foreach ($routes->getAllRoutes() as $route) { |
|
48
|
77 |
|
if ($route->requestMatches()) { |
|
49
|
72 |
|
return $route; |
|
50
|
|
|
} |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
6 |
|
return new Route('', '/', NotFound404Controller::class); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
2 |
|
private static function handleException(Handlers $handlers, Exception $exception): void |
|
57
|
|
|
{ |
|
58
|
2 |
|
$handler = $handlers->getByException($exception); |
|
59
|
2 |
|
if ($handler === null) { |
|
60
|
1 |
|
header('HTTP/1.1 500 Internal Server Error'); |
|
61
|
|
|
} else { |
|
62
|
|
|
/** @var mixed $result */ |
|
63
|
1 |
|
$result = $handler($exception); |
|
64
|
1 |
|
if (is_string($result)) { |
|
65
|
1 |
|
echo $result; |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|