49 lines
1.5 KiB
PHP
49 lines
1.5 KiB
PHP
<?php
|
|
namespace Blog\Core;
|
|
|
|
use Blog\Middleware\middlewareInterface;
|
|
use Blog\Http\request;
|
|
use Blog\Http\response;
|
|
|
|
class Router {
|
|
private array $routes = [];
|
|
|
|
public function addRoute(string $method, string $path, callable $handler, array $middlewares = []): void {
|
|
$path = preg_replace('/{(\w+)}/', '(?P<$1>[^/]+)', $path);
|
|
$this->routes[] = compact("method", "path", "handler", "middlewares");
|
|
}
|
|
|
|
public function dispatch(Request $req, Response $res): void {
|
|
$method = $req->getMethod();
|
|
$uri = $req->getPath();
|
|
|
|
foreach($this->routes as $route) {
|
|
if($route['method'] === $method && preg_match("~^" . $route['path'] . "$~", $uri, $matches)) {
|
|
array_shift($matches);
|
|
$params = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);
|
|
if(!$this->handleMiddlewares($route['middlewares'], $req, $res))
|
|
return;
|
|
call_user_func_array($route['handler'], array_merge([ $req, $res ], $params));
|
|
$res->send();
|
|
return;
|
|
}
|
|
}
|
|
|
|
$res
|
|
->setStatus(404)
|
|
->getBody()
|
|
->write("404 - Not Found")
|
|
->send();
|
|
}
|
|
|
|
private function handleMiddlewares(array $middlewares, Request $req, Response $res): bool {
|
|
foreach($middlewares as $middleware) {
|
|
$middlewareInstance = is_string($middleware) ? new $middleware() : $middleware;
|
|
if($middlewareInstance instanceof MiddlewareInterface)
|
|
if(!$middlewareInstance->handle($req, $res))
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
}
|