feat: initial commit of camelia/controllers
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.
This commit is contained in:
commit
341d1bdc2c
52 files changed
+7552
No files matched your search
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Controllers;
|
||||
|
||||
use Camelia\Controllers\Exception\HttpError;
|
||||
use Camelia\Controllers\Exception\NotFound;
|
||||
|
||||
/**
|
||||
* Base class for controllers.
|
||||
*
|
||||
* It provides response helpers and the request → response contract. It never writes to the output:
|
||||
* a handler returns a `Response` and an adapter emits it. That is what keeps every handler testable
|
||||
* without a server.
|
||||
*/
|
||||
abstract class Controller
|
||||
{
|
||||
/**
|
||||
* Dispatches one request. Concrete controllers implement their own routing.
|
||||
*/
|
||||
abstract public function render(Request $request): Response;
|
||||
|
||||
/**
|
||||
* @param array<string, string> $headers
|
||||
*/
|
||||
protected function json(mixed $data, int $status = 200, array $headers = []): Response
|
||||
{
|
||||
return new Response($data, $status, $headers);
|
||||
}
|
||||
|
||||
/**
|
||||
* A paginated collection in the shape shared with `Camelia\Orm\Pagination\Page`.
|
||||
*
|
||||
* @param list<array<string, mixed>> $items
|
||||
*/
|
||||
protected function page(array $items, int $page, int $perPage, int $total): Response
|
||||
{
|
||||
$safePage = max(1, $page);
|
||||
$safePerPage = max(1, min(1000, $perPage));
|
||||
$safeTotal = max(0, $total);
|
||||
$totalPages = (int) ceil($safeTotal / $safePerPage);
|
||||
|
||||
return $this->json([
|
||||
'items' => $items,
|
||||
'page' => $safePage,
|
||||
'per_page' => $safePerPage,
|
||||
'total' => $safeTotal,
|
||||
'total_pages' => $totalPages,
|
||||
'has_next' => $safePage < $totalPages,
|
||||
'has_prev' => $safePage > 1,
|
||||
]);
|
||||
}
|
||||
|
||||
/** 201 with a `Location` header pointing at the new resource. */
|
||||
protected function created(mixed $data, string $location): Response
|
||||
{
|
||||
return $this->json($data, 201, ['Location' => $location]);
|
||||
}
|
||||
|
||||
/** 204 with no body. */
|
||||
protected function noContent(): Response
|
||||
{
|
||||
return Response::noContent();
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns any error into a response. This method never throws, so an adapter can always rely on
|
||||
* getting a `Response` back.
|
||||
*/
|
||||
protected function error(HttpError $error): Response
|
||||
{
|
||||
return $this->json($error->toArray(), $error->status(), $error->headers());
|
||||
}
|
||||
|
||||
/** Convenience wrapper that keeps the error code consistent with the rest of the library. */
|
||||
protected function notFound(string $message): Response
|
||||
{
|
||||
return $this->error(new NotFound($message));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Controllers;
|
||||
|
||||
use Camelia\Controllers\Exception\BadRequest;
|
||||
use Camelia\Controllers\Exception\HttpError;
|
||||
use Camelia\Controllers\Exception\ServerError;
|
||||
|
||||
/**
|
||||
* Generic REST CRUD over a {@see ResourceGateway}.
|
||||
*
|
||||
* The five standard actions are wired here; a subclass only names its resource. `render()` reads
|
||||
* the method and the `id` route attribute, so the router needs nothing beyond `render($request)`.
|
||||
*/
|
||||
class CrudController extends Controller
|
||||
{
|
||||
public const DEFAULT_PER_PAGE = 20;
|
||||
public const MAX_PER_PAGE = 1000;
|
||||
|
||||
public function __construct(
|
||||
protected readonly ResourceGateway $gateway,
|
||||
protected readonly string $resource,
|
||||
) {
|
||||
if ($this->resource === '') {
|
||||
throw new BadRequest('A resource name is required.');
|
||||
}
|
||||
}
|
||||
|
||||
public function render(Request $request): Response
|
||||
{
|
||||
try {
|
||||
return $this->handle($request);
|
||||
} catch (HttpError $error) {
|
||||
return $this->error($error);
|
||||
}
|
||||
}
|
||||
|
||||
/** @return list<string> Methods this controller answers for the given id presence. */
|
||||
public function allowedMethods(bool $hasId): array
|
||||
{
|
||||
return $hasId ? ['GET', 'PUT', 'PATCH', 'DELETE'] : ['GET', 'POST'];
|
||||
}
|
||||
|
||||
public function resourceName(): string
|
||||
{
|
||||
return $this->resource;
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /recurso — paginated collection.
|
||||
*/
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
$page = $this->positiveInt($request->query('page'), 1);
|
||||
$perPage = min(self::MAX_PER_PAGE, $this->positiveInt(
|
||||
$request->query('per_page'),
|
||||
self::DEFAULT_PER_PAGE,
|
||||
));
|
||||
|
||||
$query = $this->filters($request);
|
||||
$total = $this->gateway->count($query) ?? 0;
|
||||
|
||||
$items = $this->gateway->findAll(
|
||||
$query
|
||||
+ [
|
||||
'page' => $page,
|
||||
'per_page' => $perPage,
|
||||
],
|
||||
);
|
||||
|
||||
return $this->page($items, $page, $perPage, $total);
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /recurso/{id}
|
||||
*/
|
||||
public function show(Request $request): Response
|
||||
{
|
||||
$id = $this->requireId($request);
|
||||
$record = $this->gateway->find($id);
|
||||
|
||||
if ($record === null) {
|
||||
return $this->notFound($this->missingMessage($id));
|
||||
}
|
||||
|
||||
return $this->json($record);
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /recurso — 201 plus the location of the new resource.
|
||||
*/
|
||||
public function store(Request $request): Response
|
||||
{
|
||||
$record = $this->gateway->create($request->body());
|
||||
$id = $record['id'] ?? null;
|
||||
|
||||
return $this->created($record, $this->locationFor($id));
|
||||
}
|
||||
|
||||
/**
|
||||
* PUT|PATCH /recurso/{id}
|
||||
*/
|
||||
public function update(Request $request): Response
|
||||
{
|
||||
$id = $this->requireId($request);
|
||||
$record = $this->gateway->update($id, $request->body());
|
||||
|
||||
if ($record === null) {
|
||||
return $this->notFound($this->missingMessage($id));
|
||||
}
|
||||
|
||||
return $this->json($record);
|
||||
}
|
||||
|
||||
/**
|
||||
* DELETE /recurso/{id} — 204, or 404 when nothing was removed.
|
||||
*/
|
||||
public function destroy(Request $request): Response
|
||||
{
|
||||
$id = $this->requireId($request);
|
||||
|
||||
if (!$this->gateway->delete($id)) {
|
||||
return $this->notFound($this->missingMessage($id));
|
||||
}
|
||||
|
||||
return $this->noContent();
|
||||
}
|
||||
|
||||
private function handle(Request $request): Response
|
||||
{
|
||||
$id = $request->attribute('id');
|
||||
$hasId = $id !== null;
|
||||
|
||||
return match ($request->method()) {
|
||||
'GET' => $hasId ? $this->show($request) : $this->index($request),
|
||||
'POST' => $hasId
|
||||
? throw new BadRequest('POST does not accept an id.')
|
||||
: $this->store($request),
|
||||
'PUT', 'PATCH' => $hasId
|
||||
? $this->update($request)
|
||||
: throw new BadRequest('An id is required.'),
|
||||
'DELETE' => $hasId
|
||||
? $this->destroy($request)
|
||||
: throw new BadRequest('An id is required.'),
|
||||
default => throw new ServerError(sprintf(
|
||||
'Method "%s" is not supported.',
|
||||
$request->method(),
|
||||
)),
|
||||
};
|
||||
}
|
||||
|
||||
private function requireId(Request $request): int|string
|
||||
{
|
||||
$id = $request->attribute('id');
|
||||
|
||||
if ($id === null || $id === '') {
|
||||
throw new BadRequest('An id is required.');
|
||||
}
|
||||
|
||||
return is_int($id) ? $id : (string) $id;
|
||||
}
|
||||
|
||||
private function locationFor(mixed $id): string
|
||||
{
|
||||
return '/' . trim($this->resource, '/') . ($id === null ? '' : '/' . (string) $id);
|
||||
}
|
||||
|
||||
private function missingMessage(int|string $id): string
|
||||
{
|
||||
return sprintf('%s %s does not exist.', ucfirst($this->resource), (string) $id);
|
||||
}
|
||||
|
||||
private function positiveInt(mixed $value, int $default): int
|
||||
{
|
||||
$candidate = filter_var($value, FILTER_VALIDATE_INT);
|
||||
|
||||
return $candidate === false || $candidate < 1 ? $default : $candidate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Query-string keys forwarded to the gateway as filters. Pagination keys are excluded because
|
||||
* they are consumed here.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function filters(Request $request): array
|
||||
{
|
||||
$filters = [];
|
||||
|
||||
foreach (self::FILTER_KEYS as $key) {
|
||||
$value = $request->query($key);
|
||||
|
||||
if (is_scalar($value)) {
|
||||
$filters[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $filters;
|
||||
}
|
||||
|
||||
/** @var list<string> */
|
||||
private const FILTER_KEYS = ['sort', 'order', 'q'];
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Controllers\Exception;
|
||||
|
||||
/**
|
||||
* The request was malformed or carried invalid values.
|
||||
*/
|
||||
final class BadRequest extends HttpError
|
||||
{
|
||||
public function __construct(string $message = 'The request is malformed.')
|
||||
{
|
||||
parent::__construct($message);
|
||||
}
|
||||
|
||||
public function status(): int
|
||||
{
|
||||
return 400;
|
||||
}
|
||||
|
||||
public function errorCode(): string
|
||||
{
|
||||
return 'bad_request';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Controllers\Exception;
|
||||
|
||||
/**
|
||||
* The request conflicts with current state, such as a duplicate key.
|
||||
*/
|
||||
final class Conflict extends HttpError
|
||||
{
|
||||
public function __construct(string $message = 'The request conflicts with the current state.')
|
||||
{
|
||||
parent::__construct($message);
|
||||
}
|
||||
|
||||
public function status(): int
|
||||
{
|
||||
return 409;
|
||||
}
|
||||
|
||||
public function errorCode(): string
|
||||
{
|
||||
return 'conflict';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Controllers\Exception;
|
||||
|
||||
/**
|
||||
* Base type of every exception raised by the library.
|
||||
*/
|
||||
class ControllerException extends \RuntimeException {}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Controllers\Exception;
|
||||
|
||||
/**
|
||||
* A failure with an HTTP status and a stable machine-readable code.
|
||||
*
|
||||
* The status and code are public contract: clients branch on them.
|
||||
*/
|
||||
abstract class HttpError extends ControllerException
|
||||
{
|
||||
abstract public function status(): int;
|
||||
|
||||
/** Stable snake_case identifier sent to the client, such as `not_found`. */
|
||||
abstract public function errorCode(): string;
|
||||
|
||||
/** @return array<string, string> */
|
||||
public function headers(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(): array
|
||||
{
|
||||
return ['code' => $this->errorCode(), 'message' => $this->getMessage()];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Controllers\Exception;
|
||||
|
||||
/**
|
||||
* The path exists but does not accept this verb. The `Allow` header lists the accepted ones.
|
||||
*/
|
||||
final class MethodNotAllowed extends HttpError
|
||||
{
|
||||
/** @param list<string> $allowed */
|
||||
public function __construct(
|
||||
private readonly array $allowed,
|
||||
) {
|
||||
parent::__construct(sprintf('Method not allowed. Accepted methods: %s.', implode(
|
||||
', ',
|
||||
$allowed,
|
||||
)));
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public function allowed(): array
|
||||
{
|
||||
return $this->allowed;
|
||||
}
|
||||
|
||||
public function status(): int
|
||||
{
|
||||
return 405;
|
||||
}
|
||||
|
||||
public function errorCode(): string
|
||||
{
|
||||
return 'method_not_allowed';
|
||||
}
|
||||
|
||||
/** @return array<string, string> */
|
||||
public function headers(): array
|
||||
{
|
||||
return ['Allow' => implode(', ', $this->allowed)];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Controllers\Exception;
|
||||
|
||||
/**
|
||||
* The requested resource does not exist.
|
||||
*/
|
||||
final class NotFound extends HttpError
|
||||
{
|
||||
public function __construct(string $message = 'The requested resource does not exist.')
|
||||
{
|
||||
parent::__construct($message);
|
||||
}
|
||||
|
||||
public static function resource(string $name, int|string $id): self
|
||||
{
|
||||
return new self(sprintf('%s %s does not exist.', ucfirst($name), (string) $id));
|
||||
}
|
||||
|
||||
public static function route(string $path): self
|
||||
{
|
||||
return new self(sprintf('No route matches "%s".', $path));
|
||||
}
|
||||
|
||||
public function status(): int
|
||||
{
|
||||
return 404;
|
||||
}
|
||||
|
||||
public function errorCode(): string
|
||||
{
|
||||
return 'not_found';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Controllers\Exception;
|
||||
|
||||
/**
|
||||
* An unexpected failure. When built from a throwable the client only sees a generic message, so
|
||||
* internal details never leak into a response.
|
||||
*/
|
||||
final class ServerError extends HttpError
|
||||
{
|
||||
public function __construct(
|
||||
string $message = 'An unexpected error occurred.',
|
||||
?\Throwable $previous = null,
|
||||
) {
|
||||
parent::__construct($message, 0, $previous);
|
||||
}
|
||||
|
||||
public static function fromThrowable(\Throwable $throwable): self
|
||||
{
|
||||
return new self('An unexpected error occurred.', $throwable);
|
||||
}
|
||||
|
||||
public function status(): int
|
||||
{
|
||||
return 500;
|
||||
}
|
||||
|
||||
public function errorCode(): string
|
||||
{
|
||||
return 'server_error';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Controllers\Exception;
|
||||
|
||||
/**
|
||||
* The request carries no valid authentication.
|
||||
*/
|
||||
final class Unauthorized extends HttpError
|
||||
{
|
||||
public function __construct(string $message = 'Authentication is required.')
|
||||
{
|
||||
parent::__construct($message);
|
||||
}
|
||||
|
||||
public function status(): int
|
||||
{
|
||||
return 401;
|
||||
}
|
||||
|
||||
public function errorCode(): string
|
||||
{
|
||||
return 'unauthorized';
|
||||
}
|
||||
|
||||
/** @return array<string, string> */
|
||||
public function headers(): array
|
||||
{
|
||||
return ['WWW-Authenticate' => 'Bearer'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Controllers\Exception;
|
||||
|
||||
/**
|
||||
* Input failed validation. Errors are grouped by field.
|
||||
*
|
||||
* The shape matches `Camelia\Orm\Exception\ValidationException::errors()`, so an adapter can forward
|
||||
* the ORM's errors without reshaping them.
|
||||
*/
|
||||
final class ValidationFailed extends HttpError
|
||||
{
|
||||
/** @param array<string, list<string>> $errors */
|
||||
public function __construct(
|
||||
private readonly array $errors,
|
||||
string $message = 'The submitted data is invalid.',
|
||||
) {
|
||||
parent::__construct($message);
|
||||
}
|
||||
|
||||
/** @return array<string, list<string>> */
|
||||
public function errors(): array
|
||||
{
|
||||
return $this->errors;
|
||||
}
|
||||
|
||||
public function status(): int
|
||||
{
|
||||
return 422;
|
||||
}
|
||||
|
||||
public function errorCode(): string
|
||||
{
|
||||
return 'validation_failed';
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function toArray(): array
|
||||
{
|
||||
return parent::toArray() + ['errors' => $this->errors];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Controllers;
|
||||
|
||||
/**
|
||||
* Array-backed request.
|
||||
*
|
||||
* This is what tests use and what an adapter builds from PSR-7 or superglobals. It reads only the
|
||||
* arrays it receives, so no test ever depends on process state.
|
||||
*/
|
||||
final readonly class JsonRequest implements Request
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $query
|
||||
* @param array<string, mixed> $body
|
||||
* @param array<string, string> $headers
|
||||
* @param array<string, mixed> $attributes
|
||||
*/
|
||||
public function __construct(
|
||||
private string $method = 'GET',
|
||||
private string $path = '/',
|
||||
private array $query = [],
|
||||
private array $body = [],
|
||||
private array $headers = [],
|
||||
private array $attributes = [],
|
||||
) {}
|
||||
|
||||
public function method(): string
|
||||
{
|
||||
return strtoupper($this->method);
|
||||
}
|
||||
|
||||
public function path(): string
|
||||
{
|
||||
return $this->path;
|
||||
}
|
||||
|
||||
public function query(string $key, mixed $default = null): mixed
|
||||
{
|
||||
return $this->query[$key] ?? $default;
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function body(): array
|
||||
{
|
||||
return $this->body;
|
||||
}
|
||||
|
||||
public function header(string $name): ?string
|
||||
{
|
||||
return $this->headers[strtolower($name)] ?? null;
|
||||
}
|
||||
|
||||
public function attribute(string $key): mixed
|
||||
{
|
||||
return $this->attributes[$key] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The parameter is widened to `mixed` so the copy stays a `JsonRequest`; the interface accepts
|
||||
* any value and there is no benefit in narrowing it on one implementation.
|
||||
*/
|
||||
public function withAttribute(string $key, mixed $value): static
|
||||
{
|
||||
return new self(
|
||||
method: $this->method,
|
||||
path: $this->path,
|
||||
query: $this->query,
|
||||
body: $this->body,
|
||||
headers: $this->headers,
|
||||
attributes: [$key => $value] + $this->attributes,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Controllers;
|
||||
|
||||
/**
|
||||
* Cross-cutting step that wraps a handler.
|
||||
*
|
||||
* A middleware either delegates by calling `$next($request)` or short-circuits by returning a
|
||||
* `Response` without calling it. PSR-15 shaped, minus the external dependency: the library stays
|
||||
* framework-free.
|
||||
*
|
||||
* @see \Camelia\Controllers\Pipeline which composes them.
|
||||
*/
|
||||
interface Middleware
|
||||
{
|
||||
/**
|
||||
* @param callable(Request): Response $next
|
||||
*/
|
||||
public function process(Request $request, callable $next): Response;
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Controllers\Middleware;
|
||||
|
||||
use Camelia\Controllers\Middleware;
|
||||
use Camelia\Controllers\Request;
|
||||
use Camelia\Controllers\Response;
|
||||
|
||||
/**
|
||||
* Negotiates JSON responses through the `Accept` header.
|
||||
*
|
||||
* The library only speaks JSON, so this middleware does two things: reject a client that accepts
|
||||
* JSON by no means with **406**, and label every response `Content-Type: application/json`.
|
||||
*
|
||||
* It does not compress the body. Compression is the server's job (`gzip`/`mod_deflate`), because
|
||||
* `Response` is immutable and the body is serialized by the adapter — compressing here would
|
||||
* duplicate work and break `Content-Length`.
|
||||
*
|
||||
* A request with no `Accept` header accepts anything, per RFC 9110.
|
||||
*/
|
||||
final readonly class ContentNegotiation implements Middleware
|
||||
{
|
||||
public const CONTENT_TYPE = 'application/json; charset=utf-8';
|
||||
|
||||
/**
|
||||
* @param list<string> $acceptedTypes MIME types considered acceptable in `Accept`.
|
||||
*/
|
||||
public function __construct(
|
||||
private array $acceptedTypes = ['application/json', '*/*'],
|
||||
private bool $addContentType = true,
|
||||
) {}
|
||||
|
||||
public function process(Request $request, callable $next): Response
|
||||
{
|
||||
$accept = $request->header('Accept');
|
||||
|
||||
if ($accept !== null && trim($accept) !== '' && !$this->isAcceptable($accept)) {
|
||||
return new Response(
|
||||
[
|
||||
'code' => 'not_acceptable',
|
||||
'message' => sprintf(
|
||||
'This endpoint produces %s. Accepted: %s.',
|
||||
self::CONTENT_TYPE,
|
||||
implode(', ', $this->acceptedTypes),
|
||||
),
|
||||
],
|
||||
406,
|
||||
['Accept' => implode(', ', $this->acceptedTypes)],
|
||||
);
|
||||
}
|
||||
|
||||
$response = $next($request);
|
||||
|
||||
if ($this->addContentType && !$response->hasHeader('Content-Type')) {
|
||||
return $response->withHeader('Content-Type', self::CONTENT_TYPE);
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* `Accept` is a comma-separated list; the first matching entry wins. A `q=0` entry means "not
|
||||
* acceptable", so a listed type with zero quality does not count as a match.
|
||||
*/
|
||||
private function isAcceptable(string $accept): bool
|
||||
{
|
||||
foreach (explode(',', $accept) as $entry) {
|
||||
[$type, $parameters] = array_pad(explode(';', trim($entry), 2), 2, '');
|
||||
|
||||
if (!in_array(strtolower(trim($type)), $this->acceptedTypes, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (preg_match('/q\s*=\s*([0-9.]+)/i', $parameters, $quality) === 1) {
|
||||
if ((float) $quality[1] <= 0.0) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Controllers\Middleware;
|
||||
|
||||
use Camelia\Controllers\Middleware;
|
||||
use Camelia\Controllers\Request;
|
||||
use Camelia\Controllers\Response;
|
||||
|
||||
/**
|
||||
* Records one line per request: method, path, status and elapsed milliseconds.
|
||||
*
|
||||
* The sink is a `callable`, not a PSR-3 logger, so the package keeps zero runtime dependencies. Pass
|
||||
* `$logger->log(...)` to wire any PSR-3 implementation:
|
||||
*
|
||||
* ```php
|
||||
* new Logging(static fn (string $level, string $message, array $context) =>
|
||||
* $logger->log($level, $message, $context));
|
||||
* ```
|
||||
*
|
||||
* The level comes from the status: 5xx → `error`, 4xx → `warning`, otherwise `info`.
|
||||
*/
|
||||
final readonly class Logging implements Middleware
|
||||
{
|
||||
/** @var callable(string, string, array<string, mixed>): void */
|
||||
private mixed $sink;
|
||||
|
||||
/** @var (callable(): float)|null */
|
||||
private mixed $clock;
|
||||
|
||||
/**
|
||||
* @param callable(string, string, array<string, mixed>): void $sink
|
||||
* @param (callable(): float)|null $clock Milliseconds source; `hrtime(true)` by default.
|
||||
*/
|
||||
public function __construct(callable $sink, ?callable $clock = null)
|
||||
{
|
||||
$this->sink = $sink;
|
||||
$this->clock = $clock;
|
||||
}
|
||||
|
||||
public function process(Request $request, callable $next): Response
|
||||
{
|
||||
$startedAt = $this->now();
|
||||
|
||||
try {
|
||||
$response = $next($request);
|
||||
} catch (\Throwable $exception) {
|
||||
// A middleware failure is still a request worth recording before it propagates.
|
||||
$this->record($request, 500, $startedAt);
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
$this->record($request, $response->status(), $startedAt);
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
private function record(Request $request, int $status, float $startedAt): void
|
||||
{
|
||||
$duration = round($this->now() - $startedAt, 1);
|
||||
|
||||
($this->sink)(
|
||||
self::levelFor($status),
|
||||
sprintf('%s %s %d', $request->method(), $request->path(), $status),
|
||||
[
|
||||
'method' => $request->method(),
|
||||
'path' => $request->path(),
|
||||
'status' => $status,
|
||||
'duration_ms' => $duration,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
private static function levelFor(int $status): string
|
||||
{
|
||||
if ($status >= 500) {
|
||||
return 'error';
|
||||
}
|
||||
|
||||
return $status >= 400 ? 'warning' : 'info';
|
||||
}
|
||||
|
||||
private function now(): float
|
||||
{
|
||||
if ($this->clock !== null) {
|
||||
return (float) ($this->clock)();
|
||||
}
|
||||
|
||||
return hrtime(true) / 1_000_000;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Controllers;
|
||||
|
||||
/**
|
||||
* Ordered middleware chain.
|
||||
*
|
||||
* The list is immutable: `with()` returns a copy, so a router can branch pipelines without one
|
||||
* request leaking middleware into the next. Execution is outside-in — the first middleware added is
|
||||
* the outermost wrapper.
|
||||
*/
|
||||
final readonly class Pipeline
|
||||
{
|
||||
/** @var list<Middleware> */
|
||||
private array $middlewares;
|
||||
|
||||
/** @param list<Middleware> $middlewares */
|
||||
public function __construct(array $middlewares = [])
|
||||
{
|
||||
$this->middlewares = array_values($middlewares);
|
||||
}
|
||||
|
||||
public function with(Middleware $middleware): self
|
||||
{
|
||||
return new self([...$this->middlewares, $middleware]);
|
||||
}
|
||||
|
||||
/** @return list<Middleware> */
|
||||
public function middlewares(): array
|
||||
{
|
||||
return $this->middlewares;
|
||||
}
|
||||
|
||||
public function isEmpty(): bool
|
||||
{
|
||||
return $this->middlewares === [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs `$handler` through the chain.
|
||||
*
|
||||
* @param callable(Request): Response $handler
|
||||
*/
|
||||
public function process(Request $request, callable $handler): Response
|
||||
{
|
||||
$next = $handler;
|
||||
|
||||
// Wrap from the innermost outwards so index 0 ends up outermost.
|
||||
foreach (array_reverse($this->middlewares) as $middleware) {
|
||||
$inner = $next;
|
||||
$next = static fn(Request $request): Response => $middleware->process($request, $inner);
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Controllers;
|
||||
|
||||
/**
|
||||
* Immutable input of a single HTTP request.
|
||||
*
|
||||
* Everything the library needs comes from here, never from superglobals, so a request can be built
|
||||
* by hand in a test and dispatched without a web server.
|
||||
*/
|
||||
interface Request
|
||||
{
|
||||
/** Uppercase HTTP verb: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`. */
|
||||
public function method(): string;
|
||||
|
||||
/** Path without the query string, always starting with `/`. */
|
||||
public function path(): string;
|
||||
|
||||
/** A query-string value, or `$default` when the key is absent. */
|
||||
public function query(string $key, mixed $default = null): mixed;
|
||||
|
||||
/**
|
||||
* Decoded request body.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function body(): array;
|
||||
|
||||
/** Header lookup is case-insensitive. */
|
||||
public function header(string $name): ?string;
|
||||
|
||||
/** A route parameter populated by the router, such as `id` for `/articulos/{id}`. */
|
||||
public function attribute(string $key): mixed;
|
||||
|
||||
/** Returns a copy with the attribute set; the receiver is left untouched. */
|
||||
public function withAttribute(string $key, mixed $value): static;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Controllers;
|
||||
|
||||
/**
|
||||
* Data access port for a REST resource.
|
||||
*
|
||||
* The library never talks to a database. An application implements this interface, typically by
|
||||
* adapting `Camelia\Orm\Repository`. Records are associative arrays; serializing them is the
|
||||
* controller's job, so the gateway stays free of presentation concerns.
|
||||
*/
|
||||
interface ResourceGateway
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $query
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public function findAll(array $query = []): array;
|
||||
|
||||
/** @return array<string, mixed>|null */
|
||||
public function find(int|string $id): ?array;
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $values
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function create(array $values): array;
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $values
|
||||
* @return array<string, mixed>|null
|
||||
*/
|
||||
public function update(int|string $id, array $values): ?array;
|
||||
|
||||
/** Returns true when a record was removed. */
|
||||
public function delete(int|string $id): bool;
|
||||
|
||||
/**
|
||||
* Total matching records, or `null` when the gateway cannot count them.
|
||||
*
|
||||
* @param array<string, mixed> $query
|
||||
*/
|
||||
public function count(array $query = []): ?int;
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Controllers;
|
||||
|
||||
/**
|
||||
* Immutable HTTP response.
|
||||
*
|
||||
* Nothing in this library emits it: an adapter calls `http_response_code()`, sends the headers and
|
||||
* writes `toJson()`. That separation is what makes every handler testable without a server.
|
||||
*/
|
||||
final readonly class Response
|
||||
{
|
||||
/**
|
||||
* @param array<string, string> $headers
|
||||
*/
|
||||
public function __construct(
|
||||
private mixed $body = null,
|
||||
private int $status = 200,
|
||||
private array $headers = [],
|
||||
) {}
|
||||
|
||||
public static function noContent(): self
|
||||
{
|
||||
return new self(null, 204);
|
||||
}
|
||||
|
||||
public function body(): mixed
|
||||
{
|
||||
return $this->body;
|
||||
}
|
||||
|
||||
public function status(): int
|
||||
{
|
||||
return $this->status;
|
||||
}
|
||||
|
||||
/** @return array<string, string> */
|
||||
public function headers(): array
|
||||
{
|
||||
return $this->headers;
|
||||
}
|
||||
|
||||
public function isSuccessful(): bool
|
||||
{
|
||||
return $this->status >= 200 && $this->status < 300;
|
||||
}
|
||||
|
||||
public function hasHeader(string $name): bool
|
||||
{
|
||||
return array_key_exists($name, $this->headers);
|
||||
}
|
||||
|
||||
public function withHeader(string $name, string $value): self
|
||||
{
|
||||
return new self($this->body, $this->status, [$name => $value] + $this->headers);
|
||||
}
|
||||
|
||||
/**
|
||||
* The body as JSON. A `null` body serializes to an empty string so a 204 stays bodyless.
|
||||
*/
|
||||
public function toJson(int $flags = 0): string
|
||||
{
|
||||
if ($this->body === null) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return (string) json_encode(
|
||||
$this->body,
|
||||
$flags | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR,
|
||||
);
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Controllers;
|
||||
|
||||
/**
|
||||
* A compiled route: one HTTP method, one pattern, one handler.
|
||||
*/
|
||||
final readonly class Route
|
||||
{
|
||||
/** @var list<string> Parameter names in the order they appear in the pattern. */
|
||||
private array $parameters;
|
||||
|
||||
private string $regex;
|
||||
|
||||
/**
|
||||
* @param Controller|callable(Request): Response $handler
|
||||
*/
|
||||
public function __construct(
|
||||
private string $method,
|
||||
private string $pattern,
|
||||
private mixed $handler,
|
||||
) {
|
||||
[$this->regex, $this->parameters] = self::compile($pattern);
|
||||
}
|
||||
|
||||
public function method(): string
|
||||
{
|
||||
return strtoupper($this->method);
|
||||
}
|
||||
|
||||
public function pattern(): string
|
||||
{
|
||||
return $this->pattern;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Controller|callable(Request): Response
|
||||
*/
|
||||
public function handler(): mixed
|
||||
{
|
||||
return $this->handler;
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public function parameters(): array
|
||||
{
|
||||
return $this->parameters;
|
||||
}
|
||||
|
||||
/**
|
||||
* Matches a path and returns the captured parameters, or `null` when it does not match.
|
||||
*
|
||||
* @return array<string, string>|null
|
||||
*/
|
||||
public function matches(string $path): ?array
|
||||
{
|
||||
if (preg_match($this->regex, $path, $matches) !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$captured = [];
|
||||
|
||||
foreach ($this->parameters as $parameter) {
|
||||
if (isset($matches[$parameter])) {
|
||||
$captured[$parameter] = (string) $matches[$parameter];
|
||||
}
|
||||
}
|
||||
|
||||
return $captured;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns `/articulos/{id}` into `#^/articulos/(?P<id>[^/]+)$#`.
|
||||
*
|
||||
* Literal text is escaped with `preg_quote`; only the `{name}` placeholders become capture
|
||||
* groups, which is why the two steps cannot be swapped.
|
||||
*
|
||||
* @return array{0: string, 1: list<string>}
|
||||
*/
|
||||
private static function compile(string $pattern): array
|
||||
{
|
||||
$parameters = [];
|
||||
$regex = '';
|
||||
|
||||
foreach (preg_split(
|
||||
'#(\{[a-zA-Z_][a-zA-Z0-9_]*\})#',
|
||||
$pattern,
|
||||
-1,
|
||||
PREG_SPLIT_DELIM_CAPTURE,
|
||||
) ?: [] as $part) {
|
||||
if (preg_match('#^\{([a-zA-Z_][a-zA-Z0-9_]*)\}$#', $part, $found) === 1) {
|
||||
$captured = (string) $found[1];
|
||||
$parameters[] = $captured;
|
||||
$regex .= '(?P<' . $captured . '>[^/]+)';
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$regex .= preg_quote($part, '#');
|
||||
}
|
||||
|
||||
return ['#^' . $regex . '$#', $parameters];
|
||||
}
|
||||
}
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
<?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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Controllers\Security;
|
||||
|
||||
use Camelia\Controllers\Exception\Unauthorized;
|
||||
use Camelia\Controllers\Middleware;
|
||||
use Camelia\Controllers\Request;
|
||||
use Camelia\Controllers\Response;
|
||||
|
||||
/**
|
||||
* Authenticates a `Authorization: Bearer <token>` header.
|
||||
*
|
||||
* The library owns the HTTP contract only: extracting the header, rejecting a missing or malformed
|
||||
* token with 401, and attaching the authenticated identity to the request. How a token is verified
|
||||
* (JWT, database row, static secret) is a `callable` the application supplies, so no cryptography
|
||||
* or session store is baked in here.
|
||||
*
|
||||
* ```php
|
||||
* new BearerAuth(fn (string $token): ?array => $jwt->verify($token));
|
||||
* ```
|
||||
*/
|
||||
final readonly class BearerAuth implements Middleware
|
||||
{
|
||||
/** Request attribute carrying the resolved identity. */
|
||||
public const ATTRIBUTE = 'user';
|
||||
|
||||
/** @var callable(string): (array<string, mixed>|null) */
|
||||
private mixed $resolver;
|
||||
|
||||
/**
|
||||
* @param callable(string): (array<string, mixed>|null) $resolver Returns the identity, or null
|
||||
* when the token is invalid or expired.
|
||||
*/
|
||||
public function __construct(callable $resolver)
|
||||
{
|
||||
$this->resolver = $resolver;
|
||||
}
|
||||
|
||||
public function process(Request $request, callable $next): Response
|
||||
{
|
||||
$header = $request->header('Authorization');
|
||||
|
||||
if ($header === null || $header === '') {
|
||||
return $this->reject('An Authorization header is required.');
|
||||
}
|
||||
|
||||
if (preg_match('/^Bearer\s+(\S+)$/i', $header, $matches) !== 1) {
|
||||
return $this->reject('The Authorization header must use the Bearer scheme.');
|
||||
}
|
||||
|
||||
$identity = ($this->resolver)((string) $matches[1]);
|
||||
|
||||
if (!is_array($identity)) {
|
||||
return $this->reject('The provided token is invalid or expired.');
|
||||
}
|
||||
|
||||
return $next($request->withAttribute(self::ATTRIBUTE, $identity));
|
||||
}
|
||||
|
||||
private function reject(string $message): Response
|
||||
{
|
||||
$error = new Unauthorized($message);
|
||||
|
||||
return new Response($error->toArray(), $error->status(), $error->headers());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Controllers\Security;
|
||||
|
||||
use Camelia\Controllers\Middleware;
|
||||
use Camelia\Controllers\Request;
|
||||
use Camelia\Controllers\Response;
|
||||
|
||||
/**
|
||||
* Adds CORS headers and answers `OPTIONS` preflight requests.
|
||||
*
|
||||
* A wildcard origin (`*`) is never combined with credentials: browsers reject that pair, so the
|
||||
* constructor downgrades credentials to `false` when the origin is `*`, instead of emitting an
|
||||
* invalid header.
|
||||
*/
|
||||
final readonly class Cors implements Middleware
|
||||
{
|
||||
/**
|
||||
* @param list<string> $allowedOrigins Exact origins, or `['*']`.
|
||||
* @param list<string> $allowedMethods
|
||||
* @param list<string> $allowedHeaders
|
||||
*/
|
||||
public function __construct(
|
||||
private array $allowedOrigins = ['*'],
|
||||
private array $allowedMethods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
|
||||
private array $allowedHeaders = ['Content-Type', 'Authorization'],
|
||||
private bool $allowCredentials = false,
|
||||
private int $maxAge = 86400,
|
||||
) {}
|
||||
|
||||
public function process(Request $request, callable $next): Response
|
||||
{
|
||||
$origin = $request->header('Origin');
|
||||
$headers = $this->headersFor($origin);
|
||||
|
||||
// A preflight never reaches the handler: there is nothing to authorize yet.
|
||||
if ($request->method() === 'OPTIONS') {
|
||||
return new Response(null, 204, $headers);
|
||||
}
|
||||
|
||||
$response = $next($request);
|
||||
|
||||
foreach ($headers as $name => $value) {
|
||||
$response = $response->withHeader($name, $value);
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/** @return array<string, string> */
|
||||
private function headersFor(?string $origin): array
|
||||
{
|
||||
$allowAll = in_array('*', $this->allowedOrigins, true);
|
||||
$isAllowed =
|
||||
$allowAll || $origin !== null && in_array($origin, $this->allowedOrigins, true);
|
||||
|
||||
$headers = [
|
||||
'Access-Control-Allow-Methods' => implode(', ', $this->allowedMethods),
|
||||
'Access-Control-Allow-Headers' => implode(', ', $this->allowedHeaders),
|
||||
'Access-Control-Max-Age' => (string) $this->maxAge,
|
||||
'Vary' => 'Origin',
|
||||
];
|
||||
|
||||
// Echo the exact origin when credentials are on: `*` is illegal with them.
|
||||
if ($this->allowCredentials) {
|
||||
if (!$isAllowed || $origin === null) {
|
||||
return $headers;
|
||||
}
|
||||
|
||||
return $headers
|
||||
+ [
|
||||
'Access-Control-Allow-Origin' => $origin,
|
||||
'Access-Control-Allow-Credentials' => 'true',
|
||||
];
|
||||
}
|
||||
|
||||
if ($isAllowed) {
|
||||
$headers['Access-Control-Allow-Origin'] = $allowAll ? '*' : (string) $origin;
|
||||
}
|
||||
|
||||
return $headers;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Controllers\Security;
|
||||
|
||||
use Camelia\Controllers\Exception\BadRequest;
|
||||
use Camelia\Controllers\Middleware;
|
||||
use Camelia\Controllers\Request;
|
||||
use Camelia\Controllers\Response;
|
||||
|
||||
/**
|
||||
* Fixed-window rate limiter.
|
||||
*
|
||||
* In-process only: the counter lives in a PHP array, so it resets with the process and does not
|
||||
* coordinate across workers. That is deliberate — the library has no dependency on Redis or APCu.
|
||||
*
|
||||
* shortcut: the counter is per process, so behind N workers the effective limit is N times the
|
||||
* configured one. Upgrade to a shared store (Redis/APCu) when the API runs on more than one worker.
|
||||
*/
|
||||
final class RateLimit implements Middleware
|
||||
{
|
||||
/** @var array<string, array{count: int, resetAt: int}> */
|
||||
private array $buckets = [];
|
||||
|
||||
public function __construct(
|
||||
private readonly int $limit = 60,
|
||||
private readonly int $windowSeconds = 60,
|
||||
private readonly ?\Closure $clock = null,
|
||||
private readonly ?\Closure $keyResolver = null,
|
||||
) {
|
||||
if ($this->limit < 1) {
|
||||
throw new BadRequest('The rate limit must be at least 1.');
|
||||
}
|
||||
|
||||
if ($this->windowSeconds < 1) {
|
||||
throw new BadRequest('The rate-limit window must be at least 1 second.');
|
||||
}
|
||||
}
|
||||
|
||||
public function process(Request $request, callable $next): Response
|
||||
{
|
||||
$key = $this->keyFor($request);
|
||||
$now = $this->now();
|
||||
$bucket = $this->buckets[$key] ?? null;
|
||||
|
||||
if ($bucket === null || $now >= $bucket['resetAt']) {
|
||||
$bucket = ['count' => 0, 'resetAt' => $now + $this->windowSeconds];
|
||||
}
|
||||
|
||||
$bucket['count']++;
|
||||
$this->buckets[$key] = $bucket;
|
||||
|
||||
$remaining = max(0, $this->limit - $bucket['count']);
|
||||
|
||||
$headers = [
|
||||
'X-RateLimit-Limit' => (string) $this->limit,
|
||||
'X-RateLimit-Remaining' => (string) $remaining,
|
||||
'X-RateLimit-Reset' => (string) $bucket['resetAt'],
|
||||
];
|
||||
|
||||
if ($bucket['count'] > $this->limit) {
|
||||
$retryAfter = max(1, $bucket['resetAt'] - $now);
|
||||
|
||||
return new Response(
|
||||
[
|
||||
'code' => 'too_many_requests',
|
||||
'message' => sprintf('Too many requests. Retry in %d seconds.', $retryAfter),
|
||||
],
|
||||
429,
|
||||
$headers + ['Retry-After' => (string) $retryAfter],
|
||||
);
|
||||
}
|
||||
|
||||
$response = $next($request);
|
||||
|
||||
foreach ($headers as $name => $value) {
|
||||
$response = $response->withHeader($name, $value);
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/** Seconds until the current window resets for this key; 0 when there is no active window. */
|
||||
public function resetIn(Request $request): int
|
||||
{
|
||||
$bucket = $this->buckets[$this->keyFor($request)] ?? null;
|
||||
|
||||
if ($bucket === null) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return max(0, $bucket['resetAt'] - $this->now());
|
||||
}
|
||||
|
||||
/**
|
||||
* Defaults to the client address, then falls back to a single shared bucket. The address comes
|
||||
* from a request attribute because the library never reads `$_SERVER`.
|
||||
*/
|
||||
private function keyFor(Request $request): string
|
||||
{
|
||||
if ($this->keyResolver !== null) {
|
||||
return (string) ($this->keyResolver)($request);
|
||||
}
|
||||
|
||||
$address = $request->attribute('client_ip');
|
||||
|
||||
return is_string($address) && $address !== '' ? $address : 'anonymous';
|
||||
}
|
||||
|
||||
private function now(): int
|
||||
{
|
||||
return $this->clock === null ? time() : (int) ($this->clock)();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Camelia\Controllers\Security;
|
||||
|
||||
use Camelia\Controllers\Exception\BadRequest;
|
||||
use Camelia\Controllers\Exception\Unauthorized;
|
||||
use Camelia\Controllers\Middleware;
|
||||
use Camelia\Controllers\Request;
|
||||
use Camelia\Controllers\Response;
|
||||
|
||||
/**
|
||||
* Rejects a request whose authenticated identity lacks a required role.
|
||||
*
|
||||
* Runs after {@see BearerAuth}: it reads the identity from the request attribute that middleware
|
||||
* set. It fails closed — a request with no identity is 401, never 200.
|
||||
*/
|
||||
final readonly class RequireRole implements Middleware
|
||||
{
|
||||
/** Attribute holding the identity; matches {@see BearerAuth::ATTRIBUTE}. */
|
||||
public const ATTRIBUTE = 'user';
|
||||
|
||||
/** Attribute holding the identity's roles. */
|
||||
public const ROLE_ATTRIBUTE = 'roles';
|
||||
|
||||
/** @param list<string> $roles Roles accepted; any one of them is enough. */
|
||||
public function __construct(
|
||||
private array $roles,
|
||||
) {
|
||||
if ($this->roles === []) {
|
||||
throw new BadRequest('At least one role is required.');
|
||||
}
|
||||
}
|
||||
|
||||
public function process(Request $request, callable $next): Response
|
||||
{
|
||||
$identity = $request->attribute(self::ATTRIBUTE);
|
||||
|
||||
if (!is_array($identity)) {
|
||||
return $this->error(new Unauthorized('Authentication is required.'));
|
||||
}
|
||||
|
||||
$granted = $this->rolesOf($identity);
|
||||
|
||||
foreach ($this->roles as $role) {
|
||||
if (in_array($role, $granted, true)) {
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
|
||||
return $this->error(new Unauthorized(sprintf('This action requires one of these roles: %s.', implode(
|
||||
', ',
|
||||
$this->roles,
|
||||
))));
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads roles from the identity under either `roles` or `role`. A single string is accepted so
|
||||
* an identity carrying one role does not have to be reshaped by the adapter.
|
||||
*
|
||||
* @param array<array-key, mixed> $identity
|
||||
* @return list<string>
|
||||
*/
|
||||
private function rolesOf(array $identity): array
|
||||
{
|
||||
$raw = $identity[self::ROLE_ATTRIBUTE] ?? $identity['role'] ?? [];
|
||||
|
||||
if (is_string($raw)) {
|
||||
return [$raw];
|
||||
}
|
||||
|
||||
if (!is_array($raw)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_values(array_filter($raw, is_string(...)));
|
||||
}
|
||||
|
||||
private function error(Unauthorized $error): Response
|
||||
{
|
||||
return new Response($error->toArray(), $error->status(), $error->headers());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user