184 lines
4.3 KiB
PHP
184 lines
4.3 KiB
PHP
<?php
|
|
|
|
class Router
|
|
{
|
|
/**
|
|
* List of valid HTTP verbs.
|
|
*/
|
|
private const VALID_METHODS = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'];
|
|
|
|
/**
|
|
* The tree of currently registered routes.
|
|
*/
|
|
private array $routes = [];
|
|
|
|
/**
|
|
* Store the last inserted node so we can register middleware and attributes to it.
|
|
*/
|
|
private array $last_inserted_node;
|
|
|
|
/**
|
|
* Add a route to the route tree. The route must be a URI path, and contain dynamic segments
|
|
* using a colon prefix. (:id, :slug, etc)
|
|
*
|
|
* Example:
|
|
* `$r->add($routes, 'GET', '/posts/:id', function($id) { echo "Viewing post $id"; });`
|
|
*/
|
|
public function add(string $method, string $route, callable $handler): Router
|
|
{
|
|
$this->validateMethod($method);
|
|
$this->validateRoute($route);
|
|
|
|
$segments = $route === '/' ? [''] : explode('/', trim($route, '/'));
|
|
|
|
$node = &$this->routes;
|
|
foreach ($segments as $segment) {
|
|
$segment = str_starts_with($segment, ':') ? ':x' : $segment;
|
|
if ($segment === '') continue;
|
|
$node = &$node[$segment];
|
|
}
|
|
|
|
$node[$method] = [
|
|
'handler' => $handler,
|
|
'middleware' => []
|
|
];
|
|
|
|
$this->last_inserted_node = &$node[$method];
|
|
|
|
return $this;
|
|
}
|
|
|
|
/**
|
|
* Perform a lookup in the route tree for a given method and URI. Returns an array with a result code,
|
|
* a handler if found, and any dynamic parameters. Codes are 200 for success, 404 for not found, and
|
|
* 405 for method not allowed.
|
|
*
|
|
* @return array ['code', 'handler', 'params']
|
|
*/
|
|
public function lookup(string $method, string $uri): array|int
|
|
{
|
|
$node = $this->routes;
|
|
$params = [];
|
|
|
|
if ($uri === '/') return $node[$method] ?? 405;
|
|
|
|
foreach (explode('/', trim($uri, '/')) as $segment) {
|
|
if (isset($node[$segment])) {
|
|
$node = $node[$segment];
|
|
continue;
|
|
}
|
|
|
|
if (isset($node[':x'])) {
|
|
$params[] = $segment;
|
|
$node = $node[':x'];
|
|
continue;
|
|
}
|
|
|
|
return 404;
|
|
}
|
|
|
|
$node[$method]['params'] = $params;
|
|
return $node[$method] ?? 405;
|
|
}
|
|
|
|
/**
|
|
* Add a middleware function to the last inserted node's stack.
|
|
*/
|
|
public function middleware(callable $middleware): Router
|
|
{
|
|
$this->last_inserted_node['middleware'][] = $middleware;
|
|
return $this;
|
|
}
|
|
|
|
/**
|
|
* Shorthand to register a GET route.
|
|
*/
|
|
public function get(string $route, callable $handler): Router
|
|
{
|
|
return $this->add('GET', $route, $handler);
|
|
}
|
|
|
|
/**
|
|
* Shorthand to register a POST route.
|
|
*/
|
|
public function post(string $route, callable $handler): Router
|
|
{
|
|
return $this->add('POST', $route, $handler);
|
|
}
|
|
|
|
/**
|
|
* Shorthand to register a PUT route.
|
|
*/
|
|
public function put(string $route, callable $handler): Router
|
|
{
|
|
return $this->add('PUT', $route, $handler);
|
|
}
|
|
|
|
/**
|
|
* Shorthand to register a DELETE route.
|
|
*/
|
|
public function delete(string $route, callable $handler): Router
|
|
{
|
|
return $this->add('DELETE', $route, $handler);
|
|
}
|
|
|
|
/**
|
|
* Shorthand to register a PATCH route.
|
|
*/
|
|
public function patch(string $route, callable $handler): Router
|
|
{
|
|
return $this->add('PATCH', $route, $handler);
|
|
}
|
|
|
|
/**
|
|
* Register multiple verbs to the same route.
|
|
*/
|
|
public function many(array $methods, string $route, callable $handler): Router
|
|
{
|
|
foreach ($methods as $method) $this->add($method, $route, $handler);
|
|
return $this;
|
|
}
|
|
|
|
/**
|
|
* Register all verbs to the same route.
|
|
*/
|
|
public function any(string $route, callable $handler): Router
|
|
{
|
|
foreach (SELF::VALID_METHODS as $method) $this->add($method, $route, $handler);
|
|
return $this;
|
|
}
|
|
|
|
/**
|
|
* Some pages function entirely as forms; thus we can shorthand a GET/POST route.
|
|
*/
|
|
public function form(string $route, callable $handler): Router
|
|
{
|
|
return $this->many(['GET', 'POST'], $route, $handler);
|
|
}
|
|
|
|
/**
|
|
* Validate the given method against valid HTTP verbs.
|
|
*/
|
|
private function validateMethod(string $method): void
|
|
{
|
|
if (!in_array($method, self::VALID_METHODS)) {
|
|
throw new InvalidArgumentException("Invalid HTTP method: $method");
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Validate that a new route follows expected formatting.
|
|
*/
|
|
private function validateRoute(string $route): void
|
|
{
|
|
if ($route === '') {
|
|
throw new InvalidArgumentException("Route cannot be empty");
|
|
}
|
|
|
|
// Ensure route starts with a slash
|
|
if (!str_starts_with($route, '/')) {
|
|
throw new InvalidArgumentException("Route must start with a '/'");
|
|
}
|
|
}
|
|
}
|