371 lines
11 KiB
PHP
371 lines
11 KiB
PHP
<?php
|
|
|
|
namespace MyCodebox\MariaCore;
|
|
|
|
use MyCodebox\MariaCore\Http\Request;
|
|
use MyCodebox\MariaCore\Http\Response;
|
|
|
|
/**
|
|
* Class Router
|
|
*
|
|
* Lightweight PSR-inspired router with middleware, route groups, named routes, and controller support.
|
|
*/
|
|
class Router
|
|
{
|
|
/**
|
|
* All registered routes, grouped by HTTP method.
|
|
* @var array<string, array>
|
|
*/
|
|
public array $routes = [
|
|
'GET' => [],
|
|
'POST' => [],
|
|
'PUT' => [],
|
|
'PATCH' => [],
|
|
'DELETE' => [],
|
|
'OPTIONS' => [],
|
|
];
|
|
|
|
/**
|
|
* Named routes for URL generation.
|
|
* @var array<string, array{method: string, pattern: string}>
|
|
*/
|
|
public array $namedRoutes = [];
|
|
|
|
/**
|
|
* Stack for route groups (prefixes and middleware).
|
|
* @var array<int, array{prefix: string, middleware: array}>
|
|
*/
|
|
private array $groupStack = [];
|
|
|
|
/**
|
|
* Global middleware applied to every route.
|
|
* @var callable[]
|
|
*/
|
|
private array $globalMiddleware = [];
|
|
|
|
/**
|
|
* Register a route with optional middleware.
|
|
*
|
|
* @param string $method
|
|
* @param string $pattern
|
|
* @param callable|string|array $handler
|
|
* @param array $middleware
|
|
* @return object RouteRegistrar for method chaining (->name())
|
|
*/
|
|
public function add(string $method, string $pattern, callable|string|array $handler, array $middleware = [])
|
|
{
|
|
$method = strtoupper($method);
|
|
|
|
$prefix = $this->getCurrentPrefix();
|
|
$pattern = $prefix . $pattern;
|
|
if ($pattern === '') {
|
|
$pattern = '/';
|
|
}
|
|
|
|
$groupMiddleware = $this->getCurrentGroupMiddleware();
|
|
$allMiddleware = array_merge($groupMiddleware, $middleware);
|
|
|
|
$this->routes[$method][$pattern] = [
|
|
'handler' => $handler,
|
|
'middleware' => $allMiddleware,
|
|
'name' => null,
|
|
];
|
|
|
|
// Return a RouteRegistrar object for method chaining (e.g. ->name())
|
|
return new class($this, $method, $pattern) {
|
|
private $router;
|
|
private $method;
|
|
private $pattern;
|
|
public function __construct($router, $method, $pattern)
|
|
{
|
|
$this->router = $router;
|
|
$this->method = $method;
|
|
$this->pattern = $pattern;
|
|
}
|
|
public function name(string $name)
|
|
{
|
|
$this->router->nameRoute($name, $this->method, $this->pattern);
|
|
$this->router->routes[$this->method][$this->pattern]['name'] = $name;
|
|
return $this;
|
|
}
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Register a GET route.
|
|
*/
|
|
public function get(string $pattern, callable|string|array $handler, array $middleware = [])
|
|
{
|
|
return $this->add('GET', $pattern, $handler, $middleware);
|
|
}
|
|
|
|
/**
|
|
* Register a POST route.
|
|
*/
|
|
public function post(string $pattern, callable|string|array $handler, array $middleware = [])
|
|
{
|
|
return $this->add('POST', $pattern, $handler, $middleware);
|
|
}
|
|
|
|
/**
|
|
* Register a PUT route.
|
|
*/
|
|
public function put(string $pattern, callable|string|array $handler, array $middleware = [])
|
|
{
|
|
return $this->add('PUT', $pattern, $handler, $middleware);
|
|
}
|
|
|
|
/**
|
|
* Register a PATCH route.
|
|
*/
|
|
public function patch(string $pattern, callable|string|array $handler, array $middleware = [])
|
|
{
|
|
return $this->add('PATCH', $pattern, $handler, $middleware);
|
|
}
|
|
|
|
/**
|
|
* Register a DELETE route.
|
|
*/
|
|
public function delete(string $pattern, callable|string|array $handler, array $middleware = [])
|
|
{
|
|
return $this->add('DELETE', $pattern, $handler, $middleware);
|
|
}
|
|
|
|
/**
|
|
* Register an OPTIONS route.
|
|
*/
|
|
public function options(string $pattern, callable|string|array $handler, array $middleware = [])
|
|
{
|
|
return $this->add('OPTIONS', $pattern, $handler, $middleware);
|
|
}
|
|
|
|
/**
|
|
* @var callable|null
|
|
*/
|
|
private $errorHandler = null;
|
|
|
|
/**
|
|
* Set a global error handler.
|
|
* @param callable $handler function(Request $request, \Throwable $e): Response
|
|
*/
|
|
public function setErrorHandler(callable $handler): void
|
|
{
|
|
$this->errorHandler = $handler;
|
|
}
|
|
|
|
/**
|
|
* Dispatch the router for the given request.
|
|
*
|
|
* @param Request $request
|
|
* @return Response
|
|
*/
|
|
public function dispatch(Request $request): Response
|
|
{
|
|
try {
|
|
$method = $request->getMethod();
|
|
$uri = $request->getUri();
|
|
|
|
if (!isset($this->routes[$method])) {
|
|
return new Response('Method Not Allowed', 405);
|
|
}
|
|
|
|
foreach ($this->routes[$method] as $pattern => $route) {
|
|
$params = [];
|
|
$regex = $this->convertPatternToRegex($pattern, $params);
|
|
|
|
if (preg_match($regex, $uri, $matches)) {
|
|
// Extract parameters
|
|
$params = [];
|
|
foreach ($matches as $key => $value) {
|
|
if (!is_int($key)) {
|
|
$params[$key] = $value;
|
|
}
|
|
}
|
|
|
|
$handler = $route['handler'];
|
|
$routeMiddleware = $route['middleware'] ?? [];
|
|
|
|
// Build middleware stack
|
|
$middlewareStack = array_merge(
|
|
$this->globalMiddleware,
|
|
$routeMiddleware,
|
|
[
|
|
function ($request) use ($handler, $params) {
|
|
// Controller support: "Controller@method" or [ControllerClass, method]
|
|
if (is_string($handler) && strpos($handler, '@') !== false) {
|
|
[$class, $method] = explode('@', $handler, 2);
|
|
if (class_exists($class)) {
|
|
$controller = new $class();
|
|
return $controller->$method($request, $params);
|
|
}
|
|
}
|
|
if (is_array($handler) && count($handler) === 2 && is_string($handler[0])) {
|
|
if (class_exists($handler[0])) {
|
|
$controller = new $handler[0]();
|
|
$method = $handler[1];
|
|
return $controller->$method($request, $params);
|
|
}
|
|
}
|
|
return call_user_func($handler, $request, $params);
|
|
}
|
|
]
|
|
);
|
|
|
|
// Run middleware stack
|
|
$runner = function ($request, $middlewareStack, $index = 0) use (&$runner) {
|
|
if (!isset($middlewareStack[$index])) {
|
|
throw new \RuntimeException('Middleware stack exhausted with no response.');
|
|
}
|
|
$middleware = $middlewareStack[$index];
|
|
return $middleware($request, function ($req) use ($runner, $middlewareStack, $index) {
|
|
return $runner($req, $middlewareStack, $index + 1);
|
|
});
|
|
};
|
|
|
|
return $runner($request, $middlewareStack);
|
|
}
|
|
}
|
|
|
|
return new Response('Not Found', 404);
|
|
} catch (\Throwable $e) {
|
|
if ($this->errorHandler) {
|
|
return call_user_func($this->errorHandler, $request, $e);
|
|
}
|
|
// Fallback: Standard error output
|
|
return (new Response())->withJson([
|
|
'error' => 'Internal Server Error',
|
|
'message' => $e->getMessage()
|
|
], 500);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get all registered routes.
|
|
*
|
|
* @return array
|
|
*/
|
|
public function getRoutes(): array
|
|
{
|
|
return $this->routes;
|
|
}
|
|
|
|
/**
|
|
* Group routes under a common prefix and/or middleware.
|
|
*
|
|
* @param string $prefix
|
|
* @param callable $callback
|
|
* @param array $middleware
|
|
* @return void
|
|
*/
|
|
public function group(string $prefix, callable $callback, array $middleware = []): void
|
|
{
|
|
$this->groupStack[] = [
|
|
'prefix' => $prefix,
|
|
'middleware' => $middleware,
|
|
];
|
|
$callback($this);
|
|
array_pop($this->groupStack);
|
|
}
|
|
|
|
/**
|
|
* Register a named route (internal use).
|
|
*/
|
|
public function nameRoute(string $name, string $method, string $pattern): void
|
|
{
|
|
$this->namedRoutes[$name] = [
|
|
'method' => $method,
|
|
'pattern' => $pattern,
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Generate a URL for a named route and parameters.
|
|
*
|
|
* @param string $name
|
|
* @param array $params
|
|
* @return string|null
|
|
*/
|
|
public function url(string $name, array $params = []): ?string
|
|
{
|
|
if (!isset($this->namedRoutes[$name])) {
|
|
return null;
|
|
}
|
|
$pattern = $this->namedRoutes[$name]['pattern'];
|
|
// Replace placeholders in pattern with parameters
|
|
$url = preg_replace_callback('#\{([a-zA-Z_][a-zA-Z0-9_]*)\}#', function ($matches) use (&$params) {
|
|
$key = $matches[1];
|
|
if (isset($params[$key])) {
|
|
$value = $params[$key];
|
|
unset($params[$key]);
|
|
return $value;
|
|
}
|
|
return $matches[0];
|
|
}, $pattern);
|
|
// Add remaining params as query string
|
|
if (!empty($params)) {
|
|
$url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($params);
|
|
}
|
|
return $url;
|
|
}
|
|
|
|
/**
|
|
* Add global middleware.
|
|
*
|
|
* @param callable $middleware
|
|
* @return void
|
|
*/
|
|
public function addMiddleware(callable $middleware): void
|
|
{
|
|
$this->globalMiddleware[] = $middleware;
|
|
}
|
|
|
|
/**
|
|
* Get current prefix from group stack.
|
|
*/
|
|
private function getCurrentPrefix(): string
|
|
{
|
|
$prefix = '';
|
|
foreach ($this->groupStack as $group) {
|
|
$prefix .= rtrim($group['prefix'], '/');
|
|
}
|
|
return $prefix;
|
|
}
|
|
|
|
/**
|
|
* Get all middleware from group stack.
|
|
*/
|
|
private function getCurrentGroupMiddleware(): array
|
|
{
|
|
$all = [];
|
|
foreach ($this->groupStack as $group) {
|
|
foreach ($group['middleware'] as $mw) {
|
|
$all[] = $mw;
|
|
}
|
|
}
|
|
return $all;
|
|
}
|
|
|
|
/**
|
|
* Convert a route pattern to regex and extract parameter names.
|
|
*
|
|
* Example: /user/{id} => #^/user/(?P<id>[^/]+)$#
|
|
*
|
|
* @param string $pattern
|
|
* @param array &$params
|
|
* @return string
|
|
*/
|
|
private function convertPatternToRegex(string $pattern, array &$params): string
|
|
{
|
|
// Allow constraints: {param:regex}
|
|
$regex = preg_replace_callback(
|
|
'#\{([a-zA-Z_][a-zA-Z0-9_]*)(:([^}]+))?\}#',
|
|
function ($matches) use (&$params) {
|
|
$params[] = $matches[1];
|
|
$constraint = isset($matches[3]) ? $matches[3] : '[^/]+';
|
|
return '(?P<' . $matches[1] . '>' . $constraint . ')';
|
|
},
|
|
$pattern
|
|
);
|
|
return '#^' . $regex . '$#';
|
|
}
|
|
}
|