feat: add Http router

This commit is contained in:
Keith Solomon
2026-07-06 17:58:56 -05:00
parent 3263975d2a
commit 8b83df60cd
2 changed files with 130 additions and 0 deletions
+47
View File
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace BattleForge\Http;
use InvalidArgumentException;
final class Router
{
/** @var list<array{method: string, pattern: string, handler: callable(Request, array<string, string>): Response}> */
private array $routes = [];
public function add(string $method, string $path, callable $handler): void
{
$pattern = '#^' . preg_replace('#\{([a-zA-Z_][a-zA-Z0-9_]*)\}#', '(?P<$1>[^/]+)', $path) . '$#';
$this->routes[] = [
'method' => strtoupper($method),
'pattern' => $pattern,
'handler' => $handler,
];
}
public function dispatch(Request $request): Response
{
foreach ($this->routes as $route) {
if ($route['method'] !== $request->method) {
continue;
}
if (preg_match($route['pattern'], $request->path, $matches) === 1) {
$params = [];
foreach ($matches as $key => $value) {
if (is_string($key)) {
$params[$key] = $value;
}
}
return ($route['handler'])($request, $params);
}
}
return Response::html(404, '<h1>Not found</h1>');
}
}