Framework-agnostic REST controller toolkit in vanilla PHP. - Router with path parameters, 404 and 405 with an Allow header. - Immutable Request, JsonRequest and Response; nothing is printed. - CrudController over a ResourceGateway port the application implements. - Composable Middleware/Pipeline chain. - Security middlewares: BearerAuth, RequireRole, RateLimit, Cors. - Transport middlewares: Logging, ContentNegotiation. - Nine typed HTTP exceptions with snake_case JSON bodies. - Declares PHP >=8.3 and no dependency on an ORM: ports are local. - MIT license.
163 lines
4.6 KiB
PHP
163 lines
4.6 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Camelia\Controllers;
|
|
|
|
use Camelia\Controllers\Exception\HttpError;
|
|
use Camelia\Controllers\Exception\MethodNotAllowed;
|
|
use Camelia\Controllers\Exception\NotFound;
|
|
use Camelia\Controllers\Exception\ServerError;
|
|
|
|
/**
|
|
* Route registry and dispatcher.
|
|
*
|
|
* `dispatch()` never throws: every failure becomes a `Response`, so a PHP front controller can
|
|
* write the result without wrapping anything.
|
|
*/
|
|
final class Router
|
|
{
|
|
/** @var list<Route> */
|
|
private array $routes = [];
|
|
|
|
private Pipeline $pipeline;
|
|
|
|
public function __construct(?Pipeline $pipeline = null)
|
|
{
|
|
$this->pipeline = $pipeline ?? new Pipeline();
|
|
}
|
|
|
|
/**
|
|
* Returns a copy of the router with one more middleware, outermost-last. The original router is
|
|
* untouched, so two endpoints can share routes with different security.
|
|
*/
|
|
public function withMiddleware(Middleware $middleware): self
|
|
{
|
|
$clone = clone $this;
|
|
$clone->pipeline = $this->pipeline->with($middleware);
|
|
|
|
return $clone;
|
|
}
|
|
|
|
public function pipeline(): Pipeline
|
|
{
|
|
return $this->pipeline;
|
|
}
|
|
|
|
/** @param Controller|callable(Request): Response $handler */
|
|
public function get(string $pattern, mixed $handler): self
|
|
{
|
|
return $this->add('GET', $pattern, $handler);
|
|
}
|
|
|
|
/** @param Controller|callable(Request): Response $handler */
|
|
public function post(string $pattern, mixed $handler): self
|
|
{
|
|
return $this->add('POST', $pattern, $handler);
|
|
}
|
|
|
|
/** @param Controller|callable(Request): Response $handler */
|
|
public function put(string $pattern, mixed $handler): self
|
|
{
|
|
return $this->add('PUT', $pattern, $handler);
|
|
}
|
|
|
|
/** @param Controller|callable(Request): Response $handler */
|
|
public function patch(string $pattern, mixed $handler): self
|
|
{
|
|
return $this->add('PATCH', $pattern, $handler);
|
|
}
|
|
|
|
/** @param Controller|callable(Request): Response $handler */
|
|
public function delete(string $pattern, mixed $handler): self
|
|
{
|
|
return $this->add('DELETE', $pattern, $handler);
|
|
}
|
|
|
|
/** @param Controller|callable(Request): Response $handler */
|
|
public function add(string $method, string $pattern, mixed $handler): self
|
|
{
|
|
$this->routes[] = new Route($method, $pattern, $handler);
|
|
|
|
return $this;
|
|
}
|
|
|
|
/** @return list<Route> */
|
|
public function routes(): array
|
|
{
|
|
return $this->routes;
|
|
}
|
|
|
|
public function dispatch(Request $request): Response
|
|
{
|
|
$path = $request->path();
|
|
$method = $request->method();
|
|
$allowed = [];
|
|
|
|
foreach ($this->routes as $route) {
|
|
$parameters = $route->matches($path);
|
|
|
|
if ($parameters === null) {
|
|
continue;
|
|
}
|
|
|
|
if ($route->method() !== $method) {
|
|
$allowed[] = $route->method();
|
|
|
|
continue;
|
|
}
|
|
|
|
return $this->invoke($route->handler(), $this->withParameters($request, $parameters));
|
|
}
|
|
|
|
// A matching path under another verb is a 405, not a 404: the resource exists.
|
|
if ($allowed !== []) {
|
|
$allowed = array_values(array_unique($allowed));
|
|
|
|
if (in_array('GET', $allowed, true) && !in_array('HEAD', $allowed, true)) {
|
|
$allowed[] = 'HEAD';
|
|
}
|
|
|
|
$error = new MethodNotAllowed($allowed);
|
|
|
|
return new Response($error->toArray(), $error->status(), $error->headers());
|
|
}
|
|
|
|
$error = NotFound::route($path);
|
|
|
|
return new Response($error->toArray(), $error->status(), $error->headers());
|
|
}
|
|
|
|
/**
|
|
* @param array<string, string> $parameters
|
|
*/
|
|
private function withParameters(Request $request, array $parameters): Request
|
|
{
|
|
foreach ($parameters as $key => $value) {
|
|
$request = $request->withAttribute($key, $value);
|
|
}
|
|
|
|
return $request;
|
|
}
|
|
|
|
/**
|
|
* @param Controller|callable(Request): Response $handler
|
|
*/
|
|
private function invoke(mixed $handler, Request $request): Response
|
|
{
|
|
$target = $handler instanceof Controller
|
|
? static fn(Request $request): Response => $handler->render($request)
|
|
: $handler;
|
|
|
|
try {
|
|
return $this->pipeline->process($request, $target);
|
|
} catch (HttpError $exception) {
|
|
return new Response($exception->toArray(), $exception->status(), $exception->headers());
|
|
} catch (\Throwable $exception) {
|
|
$error = ServerError::fromThrowable($exception);
|
|
|
|
return new Response($error->toArray(), $error->status(), $error->headers());
|
|
}
|
|
}
|
|
}
|