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,5 @@
|
|||||||
|
/vendor/
|
||||||
|
.phpunit.cache/
|
||||||
|
.phpunit.result.cache
|
||||||
|
.mago.cache
|
||||||
|
coverage/
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
# AGENTS.md — `camelia/controllers`
|
||||||
|
|
||||||
|
Paquete `camelia/controllers`, de Dr2g Sistemas. Namespace raíz `Camelia\Controllers` → `src/`
|
||||||
|
(PSR-4). Toolkit para construir APIs REST rápido: routing, parseo de request, validación y respuesta
|
||||||
|
JSON. **PHP vanilla**, sin framework.
|
||||||
|
|
||||||
|
## Estado del paquete
|
||||||
|
|
||||||
|
Implementado: 5 clases públicas (`Controller`, `CrudController`, `Router`, `Request`, `ResourceGateway`),
|
||||||
|
3 de soporte (`JsonRequest`, `Response`, `Route`), la cadena `Middleware`/`Pipeline`, 4 middlewares
|
||||||
|
de seguridad en `src/Security/` (`BearerAuth`, `RequireRole`, `RateLimit`, `Cors`), 2 de transporte en
|
||||||
|
`src/Middleware/` (`Logging`, `ContentNegotiation`), más 9 excepciones.
|
||||||
|
`docs/especificaciones-controllers.md` es la spec normativa; **léela antes de tocar la API**. No
|
||||||
|
inventes clases públicas sin un `S#` que las respalde.
|
||||||
|
|
||||||
|
## Documentación
|
||||||
|
|
||||||
|
| Documento | Contenido |
|
||||||
|
|---|---|
|
||||||
|
| `docs/README.md` | Índice, requisitos, inicio en 30 s, mapa de `src/` |
|
||||||
|
| `docs/GUIA-PROGRAMADOR.md` | Guía completa. **Sección 13 (trampas)** antes de escribir código |
|
||||||
|
| `docs/EJEMPLOS.md` | API de facturación de punta a punta, con adaptador de ORM y tests |
|
||||||
|
| `docs/ARQUITECTURA.md` | El porqué de cada decisión y la tabla de lo descartado |
|
||||||
|
| `docs/especificaciones-controllers.md` | Contrato normativo: nombres, formas JSON, códigos |
|
||||||
|
|
||||||
|
Al cambiar la API pública, actualiza la guía (sección 14, referencia) y la spec (§12). La tabla de
|
||||||
|
«qué se descartó» de `ARQUITECTURA.md` existe para que nadie reintroduzca las decisiones ya revertidas.
|
||||||
|
|
||||||
|
**No hay `src/classes/`**: los controllers viven en `src/` raíz bajo PSR-4. Si ves rutas con
|
||||||
|
`classes/` en un prompt, son restos de un andamiaje vacío que se eliminó.
|
||||||
|
|
||||||
|
## Hermano con convenciones ya fijadas
|
||||||
|
|
||||||
|
`../orm` (`camelia/orm`) es el paquete que fija el estilo. Su `AGENTS.md` y su
|
||||||
|
`especificaciones-orm.md` son la referencia: toolchain, gate, nomenclatura y trampas son las mismas
|
||||||
|
salvo lo que difiere abajo. Léelos antes de tocar el toolchain.
|
||||||
|
|
||||||
|
| | aquí | en `../orm` |
|
||||||
|
|---|---|---|
|
||||||
|
| PHP declarado | `>=8.3` | `>=8.3` (su prosa dice 8.2: gana el composer.json) |
|
||||||
|
| Parser Mago / PHPStan | 8.2 / `80300` | 8.2 / `80200` |
|
||||||
|
| `mago-baseline.toml` | **no existe**, y no debe crearse | existe |
|
||||||
|
|
||||||
|
## Independencia del ORM (decisión de diseño, no descuido)
|
||||||
|
|
||||||
|
`composer.json` **no** requiere `camelia/orm`. La librería define sus propios puertos (interfaces) y
|
||||||
|
la app conecta el ORM por composición. Consecuencias que un agente rompería por instinto:
|
||||||
|
|
||||||
|
- No importes `Camelia\Orm\*` en `src/`. Ni siquiera en docblocks, salvo como ejemplo marcado.
|
||||||
|
- No envuelvas `Repository` ni `Page`. Si necesitas paginación, declara tu propio contrato; que el
|
||||||
|
adaptador del ORM lo implemente es problema de la app.
|
||||||
|
- Los errores de dominio llegan como excepciones propias de la librería, nunca como
|
||||||
|
`Camelia\Orm\Exception\*`. El mapeo a HTTP vive dentro de este paquete.
|
||||||
|
|
||||||
|
## Nomenclatura (heredada del glosario del ORM)
|
||||||
|
|
||||||
|
- Lecturas: prefijo `find`. Escrituras: verbo de destino. Un `find*` **nunca** escribe ni envía.
|
||||||
|
- `...Column()` devuelve columna SQL; sin sufijo devuelve propiedad PHP.
|
||||||
|
- Booleanos con `is`/`has`/`can`. Colecciones en plural.
|
||||||
|
- Sin abreviaturas: `Request`, no `Req`; `Response`, no `Resp`; `Controller`, no `Ctrl`.
|
||||||
|
- La implementación lleva el prefijo del origen (`JsonRequestParser`), la interfaz el rol
|
||||||
|
(`RequestParser`).
|
||||||
|
- Respuestas y errores en JSON con `snake_case` en las claves (igual que `Page::toArray()` del ORM:
|
||||||
|
`per_page`, `total_pages`, `has_next`). El código PHP usa `camelCase`.
|
||||||
|
|
||||||
|
## Entorno local
|
||||||
|
|
||||||
|
- PHP: `C:\php8.4\php.exe` (8.4.19), Composer 2.10.3. La librería declara `>=8.3`, así que **no**
|
||||||
|
uses sintaxis exclusiva de 8.4; por eso `(new Foo())->bar()` conserva los paréntesis.
|
||||||
|
- `declare(strict_types=1)` en todo archivo, incluidos los tests.
|
||||||
|
- Sin `.env` ni servicios externos. Los tests son unitarios y puros: no levantan servidor, ni base,
|
||||||
|
ni red. Un test que necesite un socket real está mal ubicado aquí.
|
||||||
|
- No hay repositorio git en este directorio ni en `C:\workspaces\ws_azulerp`; no intentes `git log`
|
||||||
|
para reconstruir historia.
|
||||||
|
|
||||||
|
## Gate antes de commitear
|
||||||
|
|
||||||
|
```bash
|
||||||
|
composer check # fmt:check -> lint -> analyze -> phpstan -> test
|
||||||
|
```
|
||||||
|
|
||||||
|
Orden obligatorio; nunca mergees con uno en rojo. Un test individual:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
vendor/bin/phpunit --configuration phpunit.xml.dist --filter NombreDelTest
|
||||||
|
```
|
||||||
|
|
||||||
|
## Trampas del toolchain
|
||||||
|
|
||||||
|
- **`php-version = "8.2"` en `mago.toml` es obligatorio.** Subirlo a 8.4 hace que `mago fmt`
|
||||||
|
reescriba `(new X())->m()` como `new X()->m()`, que rompe el soporte declarado y ni siquiera parsea
|
||||||
|
cuando el resultado se asigna.
|
||||||
|
- `mago analyze` excluye `tests/` (no carga el autoloader de Composer): reportaría `TestCase` como
|
||||||
|
clase inexistente. PHPStan sí cubre los tests.
|
||||||
|
- **Sin baseline.** El baseline del ORM acepta `mixed` inherente a PDO. Aquí no hay PDO como
|
||||||
|
fuente de datos: un `mixed` nuevo es un error real, no un hallazgo a aceptar. Si te tienta crear
|
||||||
|
`mago-baseline.toml`, primero justifícalo en la spec.
|
||||||
|
- `failOnWarning`, `failOnRisky` y `failOnEmptyTestSuite` están activos: un test sin asserts o un
|
||||||
|
suite vacío rompen el gate.
|
||||||
|
|
||||||
|
## Trampas de implementación (todas verificadas por los tests)
|
||||||
|
|
||||||
|
- El controller **no** imprime ni hace `echo`/`header()`. Devuelve `Response`; el adaptador la emite
|
||||||
|
con `http_response_code()` + `toJson()`. Un handler que escribe en el output rompe los tests.
|
||||||
|
- El request entra por `Request`/`JsonRequest`, nunca por superglobales.
|
||||||
|
- **`catch (HttpError)` necesita su `use`.** `Router::invoke()` resuelve `HttpError` a
|
||||||
|
`Camelia\Controllers\Exception\HttpError`; sin el import, el catch nunca coincide y un 404 sale como
|
||||||
|
500. Ya pasó una vez.
|
||||||
|
- `Route::compile()` escapa el literal con `preg_quote` y solo después inserta los grupos `{name}`.
|
||||||
|
Invertir el orden rompe los puntos y los guiones de un path como `/archivos/reporte.json`.
|
||||||
|
- `CrudController::render()` lee `attribute('id')`, que **solo** puebla el `Router`. Llamar
|
||||||
|
`render()` a mano en un test sin `withAttribute('id', ...)` devuelve 400, no 200.
|
||||||
|
- `CrudController::index()` reenvía `sort`, `order` y `q` al gateway como filtros; `page`/`per_page`
|
||||||
|
los consume él.
|
||||||
|
- `RateLimit` guarda su contador en memoria del proceso: detrás de N workers el límite efectivo es
|
||||||
|
N×. Es una `shortcut:` deliberada, documentada en el código.
|
||||||
|
- `Cors` va **antes** que `BearerAuth` en el pipeline: si va después, el preflight `OPTIONS` se come
|
||||||
|
un 401 y el navegador nunca envía la petición real.
|
||||||
|
- `RequireRole` lee el atributo `user` que pone `BearerAuth`. Usarlo sin `BearerAuth` delante da 401
|
||||||
|
siempre, por diseño (falla cerrado).
|
||||||
|
- Ningún `die`/`exit`. Los códigos de status y las formas JSON de §12 son contrato público.
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 Dario Garcia
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# camelia/controllers
|
||||||
|
|
||||||
|
Framework-agnostic REST controller toolkit: routing, request parsing, validation and JSON responses
|
||||||
|
over any data source. Vanilla PHP, no framework.
|
||||||
|
|
||||||
|
- **Package:** `camelia/controllers` — **Namespace:** `Camelia\Controllers`
|
||||||
|
- **PHP** `>=8.3`, extension `json`
|
||||||
|
|
||||||
|
## What it is
|
||||||
|
|
||||||
|
The HTTP layer of a REST API, and nothing else:
|
||||||
|
|
||||||
|
- **Routing** with parameters (`/articulos/{id}`), plus 404 and 405 responses with an `Allow` header.
|
||||||
|
- **Immutable request and response** objects. Nothing is printed; a `Response` is returned and the
|
||||||
|
adapter emits it.
|
||||||
|
- **Generic CRUD** over a `ResourceGateway` port that the application implements.
|
||||||
|
- **Composable middlewares:** authentication, roles, rate limiting, CORS, logging, content
|
||||||
|
negotiation.
|
||||||
|
|
||||||
|
## What it is not
|
||||||
|
|
||||||
|
Not a framework. No dependency-injection container, no ORM, no templating. The package declares its
|
||||||
|
own ports; if an application uses an ORM, it connects it by composition.
|
||||||
|
|
||||||
|
## Install
|
||||||
|
|
||||||
|
```bash
|
||||||
|
composer require camelia/controllers
|
||||||
|
```
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
|
||||||
|
The full developer guide, organised by task, is in
|
||||||
|
[`docs/GUIA-PROGRAMADOR.md`](docs/GUIA-PROGRAMADOR.md). The normative contract — public names, JSON
|
||||||
|
shapes and status codes — is [`docs/especificaciones-controllers.md`](docs/especificaciones-controllers.md).
|
||||||
|
|
||||||
|
The documentation index lives in [`docs/README.md`](docs/README.md).
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
```bash
|
||||||
|
composer install
|
||||||
|
composer check # fmt:check -> lint -> analyze -> phpstan -> test
|
||||||
|
```
|
||||||
|
|
||||||
|
`composer check` must be green before anything is merged, and the steps run in that order.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
MIT. See [LICENSE](LICENSE).
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
{
|
||||||
|
"name": "camelia/controllers",
|
||||||
|
"description": "Framework-agnostic REST controller toolkit: routing, request parsing, validation and JSON responses over any data source.",
|
||||||
|
"type": "library",
|
||||||
|
"license": "MIT",
|
||||||
|
"keywords": ["rest", "controller", "api", "http", "router"],
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "Dario Garcia",
|
||||||
|
"email": "dario61081@gmail.com"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"require": {
|
||||||
|
"php": ">=8.3",
|
||||||
|
"ext-json": "*"
|
||||||
|
},
|
||||||
|
"require-dev": {
|
||||||
|
"carthage-software/mago": "^1.60",
|
||||||
|
"phpstan/phpstan": "^1.11",
|
||||||
|
"phpunit/phpunit": "^10.5 || ^11.0"
|
||||||
|
},
|
||||||
|
"autoload": {
|
||||||
|
"psr-4": {
|
||||||
|
"Camelia\\Controllers\\": "src/"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"autoload-dev": {
|
||||||
|
"psr-4": {
|
||||||
|
"Camelia\\Controllers\\Tests\\": "tests/"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"test": "phpunit --configuration phpunit.xml.dist",
|
||||||
|
"fmt": "mago fmt",
|
||||||
|
"fmt:check": "mago fmt --check",
|
||||||
|
"lint": "mago lint",
|
||||||
|
"analyze": "mago analyze",
|
||||||
|
"phpstan": "php -d memory_limit=1G vendor/bin/phpstan analyse --configuration phpstan.neon --no-progress",
|
||||||
|
"check": [
|
||||||
|
"@fmt:check",
|
||||||
|
"@lint",
|
||||||
|
"@analyze",
|
||||||
|
"@phpstan",
|
||||||
|
"@test"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"config": {
|
||||||
|
"sort-packages": true
|
||||||
|
},
|
||||||
|
"minimum-stability": "stable",
|
||||||
|
"prefer-stable": true,
|
||||||
|
"archive": {
|
||||||
|
"exclude": [
|
||||||
|
"/tests",
|
||||||
|
"/mago.toml",
|
||||||
|
"/phpstan.neon",
|
||||||
|
"/phpunit.xml.dist",
|
||||||
|
"/AGENTS.md",
|
||||||
|
"/.gitignore"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"extra": {
|
||||||
|
"branch-alias": {
|
||||||
|
"dev-main": "1.0.x-dev"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Generated
+1975
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,205 @@
|
|||||||
|
# Arquitectura de `camelia/controllers`
|
||||||
|
|
||||||
|
Por qué la librería es como es, y qué se descartó a propósito.
|
||||||
|
|
||||||
|
## El problema
|
||||||
|
|
||||||
|
Construir una API REST en PHP vanilla termina siempre en el mismo código, copiado endpoint por
|
||||||
|
endpoint:
|
||||||
|
|
||||||
|
```php
|
||||||
|
// el clásico
|
||||||
|
header('Content-Type: application/json');
|
||||||
|
http_response_code(200);
|
||||||
|
echo json_encode($datos);
|
||||||
|
```
|
||||||
|
|
||||||
|
Ese patrón tiene tres defectos que no se ven hasta que el proyecto crece:
|
||||||
|
|
||||||
|
1. **No se puede testear.** Para verificar que un endpoint devuelve 404 hay que levantar un servidor.
|
||||||
|
2. **El status se decide en tres lugares.** `header()`, `http_response_code()` y el cuerpo pueden
|
||||||
|
contradecirse, y nada lo detecta.
|
||||||
|
3. **`$_GET`, `$_POST`, `$_SERVER` aparecen en todas partes.** Ningún test reproduce un request sin
|
||||||
|
manipular estado global.
|
||||||
|
|
||||||
|
La librería ataca los tres: un `Request` de entrada, un `Response` de salida, y el despacho en medio.
|
||||||
|
|
||||||
|
## El flujo
|
||||||
|
|
||||||
|
```
|
||||||
|
entorno web tu app la librería
|
||||||
|
┌──────────────────────┐ ┌─────────────────────┐
|
||||||
|
│ $_SERVER, php://input│───────▶│ JsonRequest │
|
||||||
|
└──────────────────────┘ └──────────┬──────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌────────────────────────┐
|
||||||
|
│ Router::dispatch() │
|
||||||
|
└────────────┬───────────┘
|
||||||
|
│
|
||||||
|
┌─────────────────▼──────────────────┐
|
||||||
|
│ Pipeline │
|
||||||
|
│ ContentNegotiation → Cors → │
|
||||||
|
│ RateLimit → BearerAuth → │
|
||||||
|
│ RequireRole → handler │
|
||||||
|
└─────────────────┬──────────────────┘
|
||||||
|
│
|
||||||
|
┌────────────▼───────────┐
|
||||||
|
│ Response (inmutable) │
|
||||||
|
└────────────┬───────────┘
|
||||||
|
│
|
||||||
|
┌──────────────────────┐ ┌──────────▼───────────┐
|
||||||
|
│ http_response_code, │◀───────│ tu index.php │
|
||||||
|
│ header, echo │ └──────────────────────┘
|
||||||
|
└──────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
La frontera está clara: **toda** la traducción del entorno ocurre en tu `index.php`, en las dos
|
||||||
|
puntas. La librería ve solo arrays.
|
||||||
|
|
||||||
|
## Principios y cómo se materializan
|
||||||
|
|
||||||
|
| Principio | Cómo |
|
||||||
|
|---|---|
|
||||||
|
| **SoC** | Entrada (`Request`), despacho (`Router`), corte transversal (`Middleware`), salida (`Response`). Ningún componente hace dos cosas. |
|
||||||
|
| **Inmutabilidad** | `Request`, `Response`, `Route`, `Pipeline` y todos los middlewares salvo `RateLimit` son `readonly`. Una respuesta no se muta: se copia con `withHeader()`. |
|
||||||
|
| **Fail loud** | Todo error lanza y llega a `HttpError`. No hay un `catch` que devuelva `[]` o 200 vacío. |
|
||||||
|
| **Sin dependencias** | `composer.json` no declara ninguna de runtime. Ni PSR-7, ni PSR-15, ni `psr/log`. |
|
||||||
|
| **Frontera de seguridad** | El detalle interno de una excepción **nunca** llega al cliente: `ServerError` sustituye el mensaje. |
|
||||||
|
|
||||||
|
## Decisiones de diseño
|
||||||
|
|
||||||
|
### 1. `Request` es una interfaz, no un DTO
|
||||||
|
|
||||||
|
Alternativa descartada: una sola clase concreta que lea `$_SERVER` por dentro.
|
||||||
|
|
||||||
|
Se eligió la interfaz por dos razones. Primero, un adaptador PSR-7 puede implementarla sin tocar la
|
||||||
|
librería. Segundo, los tests construyen la implementación concreta con arrays literales — nada de
|
||||||
|
variables globales.
|
||||||
|
|
||||||
|
El costo es una capa extra: `Request` + `JsonRequest`. Se aceptó.
|
||||||
|
|
||||||
|
### 2. `Response` es `final readonly` con cuerpo `mixed`
|
||||||
|
|
||||||
|
Alternativa descartada: subclases `JsonResponse`, `HtmlResponse`, `EmptyResponse`.
|
||||||
|
|
||||||
|
Un solo tipo con `body: mixed` cubre todo lo que una API JSON necesita, y evita una jerarquía que
|
||||||
|
crece con cada formato. `Response::noContent()` es el atajo para el caso vacío.
|
||||||
|
|
||||||
|
`toJson()` es **explícito**: no hay `__toString()`. Serializar es una decisión, no un efecto de
|
||||||
|
concatenar.
|
||||||
|
|
||||||
|
### 3. El CRUD depende de un puerto, no del ORM
|
||||||
|
|
||||||
|
Alternativa descartada: `require camelia/orm` y usar `Repository` directo.
|
||||||
|
|
||||||
|
Era la opción más corta y se descartó a propósito. Acoplar la capa HTTP al ORM significa que la
|
||||||
|
librería de controllers no se puede usar con otro origen de datos, y que un cambio en el ORM rompe la
|
||||||
|
API. Con `ResourceGateway`, el adaptador es de la app: unas 40 líneas, una vez por recurso.
|
||||||
|
|
||||||
|
Consecuencia que suele sorprender: `find()` y `update()` devuelven `null`, **no** lanzan. El 404 lo
|
||||||
|
decide el controller. Un gateway que lanza excepciones HTTP mezclaría dos capas.
|
||||||
|
|
||||||
|
### 4. Los middlewares son una interfaz, no un trait
|
||||||
|
|
||||||
|
Alternativa descartada: `trait MiddlewareHelpers` con un método `next()`.
|
||||||
|
|
||||||
|
El trait obliga a herencia y hace imposible componer dos middlewares que ambos lo usen. La interfaz
|
||||||
|
con `callable $next` es la forma PSR-15, ya conocida, y permite closures y clases indistintamente.
|
||||||
|
|
||||||
|
`Pipeline` existe porque un `array` de middlewares no sabe ejecutarse. Encapsular la recursión en un
|
||||||
|
objeto inmutable evita el bug clásico de mutar la lista compartida entre requests.
|
||||||
|
|
||||||
|
### 5. `BearerAuth` no implementa JWT
|
||||||
|
|
||||||
|
Alternativa descartada: incluir verificación de firma con `firebase/php-jwt`.
|
||||||
|
|
||||||
|
Decidir el algoritmo, el manejo de claves y la revocación es responsabilidad de la app, no de una
|
||||||
|
librería de capa HTTP. La librería aporta lo que sí le corresponde: extraer el header, rechazar con el
|
||||||
|
status correcto y adjuntar la identidad. La verificación entra como `callable`.
|
||||||
|
|
||||||
|
Esto también mantiene la regla de cero dependencias.
|
||||||
|
|
||||||
|
### 6. `RequireRole` devuelve 401, no 403
|
||||||
|
|
||||||
|
Decisión deliberada. Un 403 confirma que el recurso existe y que el usuario está autenticado pero no
|
||||||
|
autorizado, lo cual filtra información a un atacante que enumera recursos.
|
||||||
|
|
||||||
|
Se eligió 401 por consistencia: no revelar si el recurso existe. Si tu API necesita 403 por razones
|
||||||
|
de producto (mensajes distintos en la UI), hay que cambiarlo, y es un cambio de contrato público.
|
||||||
|
|
||||||
|
### 7. `RateLimit` guarda estado en memoria
|
||||||
|
|
||||||
|
Alternativa descartada: añadir `predis/predis` o depender de APCu.
|
||||||
|
|
||||||
|
Ambas rompen «cero dependencias». La limitación (N workers → N× el límite) está documentada como
|
||||||
|
`shortcut:` en el código, con la condición de cuándo upgradear. Preferible una limitación honesta y
|
||||||
|
documentada que una dependencia escondida.
|
||||||
|
|
||||||
|
### 8. `ContentNegotiation` no comprime
|
||||||
|
|
||||||
|
Alternativa descartada: un middleware `Compression` que haga `gzencode()`.
|
||||||
|
|
||||||
|
`Response` es inmutable y el cuerpo se serializa en el adaptador. Comprimir dentro del middleware
|
||||||
|
implicaría serializar dos veces y dejar un `Content-Length` que no coincide con el cuerpo emitido — un
|
||||||
|
bug de transporte disfrazado de feature. La compresión HTTP es del servidor (`gzip`, `mod_deflate`).
|
||||||
|
|
||||||
|
Lo que sí le toca a la librería es negociar el formato, y eso es lo que hace: 406 cuando el cliente no
|
||||||
|
acepta JSON, `Content-Type` correcto en toda respuesta.
|
||||||
|
|
||||||
|
### 9. `Router::dispatch()` nunca lanza
|
||||||
|
|
||||||
|
Es deliberado que `dispatch()` capture `Throwable` y devuelva 500. Un front controller de tres líneas
|
||||||
|
no debería envolver en `try/catch`: si el dispatch lanzara, cada app tendría que repetir el mismo
|
||||||
|
manejo.
|
||||||
|
|
||||||
|
Excepción de la excepción: `Response::toJson()` puede lanzar `JsonException` si el cuerpo no es
|
||||||
|
codificable, y eso ocurre en el `echo` de tu `index.php`, fuera del `try` del router. Una respuesta
|
||||||
|
con `NAN`, un recurso o UTF-8 inválido falla ahí.
|
||||||
|
|
||||||
|
## El grafo de dependencias
|
||||||
|
|
||||||
|
```
|
||||||
|
Controller ─────────────▶ Response
|
||||||
|
│
|
||||||
|
Router ────▶ Route, Pipeline ────▶ Middleware (interfaz)
|
||||||
|
│ │
|
||||||
|
└──▶ Response Security/*, Middleware/*
|
||||||
|
│
|
||||||
|
└──▶ Request, Response, Exception/*
|
||||||
|
CrudController ────▶ Controller, ResourceGateway
|
||||||
|
```
|
||||||
|
|
||||||
|
Nada apunta hacia arriba. `ResourceGateway` y `Request` son interfaces puras: no importan nada de la
|
||||||
|
librería salvo tipos de escalares.
|
||||||
|
|
||||||
|
## Qué se descartó y no conviene reintroducir
|
||||||
|
|
||||||
|
| Descartado | Por qué |
|
||||||
|
|---|---|
|
||||||
|
| `echo` / `header()` dentro de la librería | Rompe el testeo sin servidor. |
|
||||||
|
| Superglobales en cualquier clase | Mismo motivo, y hace que dos requests compartan estado. |
|
||||||
|
| `abstract BaseController` con `index/show/store` | `CrudController` ya lo es; una segunda capa de herencia no aporta. |
|
||||||
|
| Jerarquía `JsonResponse`/`HtmlResponse` | Un tipo con `body: mixed` cubre el caso. |
|
||||||
|
| `require camelia/orm` | Acopla la capa HTTP a un origen de datos. |
|
||||||
|
| PSR-7/PSR-15 reales | Dos dependencias para reimplementar metadatos triviales. La forma se imita, no se importa. |
|
||||||
|
| `psr/log` obligatorio | Una interfaz de un método no justifica una dependencia; un `callable` basta. |
|
||||||
|
| Orden de middlewares automático | El orden tiene consecuencias reales; que lo declare quien lo entiende. |
|
||||||
|
|
||||||
|
## Verificación
|
||||||
|
|
||||||
|
| Comprobación | Comando |
|
||||||
|
|---|---|
|
||||||
|
| Tests | `composer test` |
|
||||||
|
| Análisis estático (nivel 8) | `composer phpstan` |
|
||||||
|
| Formato, lint, analyze | `composer fmt:check`, `composer lint`, `composer analyze` |
|
||||||
|
| Todo junto | `composer check` |
|
||||||
|
|
||||||
|
`composer check` exige Mago instalado y funcionando. En un entorno sin acceso al binario, PHPStan y
|
||||||
|
PHPUnit cubren la mayor parte.
|
||||||
|
|
||||||
|
## Por dónde seguir
|
||||||
|
|
||||||
|
- **[GUIA-PROGRAMADOR.md](GUIA-PROGRAMADOR.md)** — uso paso a paso.
|
||||||
|
- **[EJEMPLOS.md](EJEMPLOS.md)** — una app completa.
|
||||||
|
- **[especificaciones-controllers.md](especificaciones-controllers.md)** — el contrato normativo.
|
||||||
@@ -0,0 +1,547 @@
|
|||||||
|
# Ejemplos — una API de facturación de punta a punta
|
||||||
|
|
||||||
|
Una aplicación completa y funcional: artículos, clientes y facturas, con seguridad, paginación y
|
||||||
|
tests. Todo el código es ejecutable tal cual.
|
||||||
|
|
||||||
|
## Estructura
|
||||||
|
|
||||||
|
```
|
||||||
|
app/
|
||||||
|
├── index.php punto de entrada
|
||||||
|
├── Gateway/
|
||||||
|
│ ├── ArticuloGateway.php adaptador sobre camelia/orm
|
||||||
|
│ └── ClienteGateway.php
|
||||||
|
└── Http/
|
||||||
|
├── ArticuloController.php
|
||||||
|
└── ClienteController.php
|
||||||
|
tests/
|
||||||
|
└── ApiTest.php
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. El punto de entrada
|
||||||
|
|
||||||
|
`app/index.php` traduce el entorno web a `Request`, despacha y emite. Es la **única** parte de la app
|
||||||
|
que toca superglobales.
|
||||||
|
|
||||||
|
```php
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
require __DIR__ . '/../vendor/autoload.php';
|
||||||
|
|
||||||
|
use App\Gateway\ArticuloGateway;
|
||||||
|
use App\Gateway\ClienteGateway;
|
||||||
|
use App\Http\ArticuloController;
|
||||||
|
use App\Http\ClienteController;
|
||||||
|
use App\Model\Articulo;
|
||||||
|
use App\Model\Cliente;
|
||||||
|
use App\Support\Jwt;
|
||||||
|
use Camelia\Controllers\Exception\Unauthorized;
|
||||||
|
use Camelia\Controllers\JsonRequest;
|
||||||
|
use Camelia\Controllers\Middleware\ContentNegotiation;
|
||||||
|
use Camelia\Controllers\Middleware\Logging;
|
||||||
|
use Camelia\Controllers\Router;
|
||||||
|
use Camelia\Controllers\Security\BearerAuth;
|
||||||
|
use Camelia\Controllers\Security\Cors;
|
||||||
|
use Camelia\Controllers\Security\RateLimit;
|
||||||
|
use Camelia\Orm\Orm;
|
||||||
|
|
||||||
|
// --- 1. Infraestructura -------------------------------------------------
|
||||||
|
$orm = Orm::fromEnvironment();
|
||||||
|
$articulos = new ArticuloController(new ArticuloGateway($orm->repository(Articulo::class)));
|
||||||
|
$clientes = new ClienteController(new ClienteGateway($orm->repository(Cliente::class)));
|
||||||
|
|
||||||
|
// --- 2. Verificación del token (decisión de la app) ----------------------
|
||||||
|
$verify = static function (string $token): ?array {
|
||||||
|
try {
|
||||||
|
return Jwt::decode($token, getenv('JWT_SECRET'));
|
||||||
|
} catch (\Throwable) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- 3. Router con la cadena completa ------------------------------------
|
||||||
|
$router = (new Router())
|
||||||
|
->withMiddleware(new ContentNegotiation())
|
||||||
|
->withMiddleware(new Cors(allowedOrigins: [getenv('APP_ORIGIN') ?: '*']))
|
||||||
|
->withMiddleware(new RateLimit(limit: 120, windowSeconds: 60))
|
||||||
|
->withMiddleware(new BearerAuth($verify))
|
||||||
|
->withMiddleware(new Logging(static function (string $level, string $message, array $context): void {
|
||||||
|
error_log(sprintf('[%s] %s %s', $level, $message, json_encode($context)));
|
||||||
|
}));
|
||||||
|
|
||||||
|
$router
|
||||||
|
->get('/articulos', $articulos)
|
||||||
|
->post('/articulos', $articulos)
|
||||||
|
->get('/articulos/{id}', $articulos)
|
||||||
|
->put('/articulos/{id}', $articulos)
|
||||||
|
->delete('/articulos/{id}', $articulos)
|
||||||
|
->get('/clientes', $clientes)
|
||||||
|
->post('/clientes', $clientes)
|
||||||
|
->get('/clientes/{id}', $clientes)
|
||||||
|
->delete('/clientes/{id}', $clientes);
|
||||||
|
|
||||||
|
// --- 4. Traducción del entorno ------------------------------------------
|
||||||
|
$headers = [];
|
||||||
|
|
||||||
|
foreach ($_SERVER as $key => $value) {
|
||||||
|
// HTTP_ORIGIN => origin, HTTP_X_TRACE_ID => x-trace-id
|
||||||
|
if (str_starts_with($key, 'HTTP_')) {
|
||||||
|
$headers[strtolower(str_replace('_', '-', substr($key, 5)))] = (string) $value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$request = new JsonRequest(
|
||||||
|
method: $_SERVER['REQUEST_METHOD'] ?? 'GET',
|
||||||
|
path: parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/',
|
||||||
|
query: $_GET,
|
||||||
|
body: json_decode(file_get_contents('php://input') ?: '{}', true) ?: [],
|
||||||
|
headers: $headers,
|
||||||
|
);
|
||||||
|
|
||||||
|
// --- 5. Emisión ---------------------------------------------------------
|
||||||
|
$response = $router->dispatch($request);
|
||||||
|
|
||||||
|
http_response_code($response->status());
|
||||||
|
|
||||||
|
foreach ($response->headers() as $name => $value) {
|
||||||
|
header($name . ': ' . $value);
|
||||||
|
}
|
||||||
|
|
||||||
|
echo $response->toJson();
|
||||||
|
```
|
||||||
|
|
||||||
|
> **Por qué el `foreach` de cabeceras.** PHP entrega cada cabecera como `HTTP_<NOMBRE>` con guiones
|
||||||
|
> bajos. `JsonRequest::header()` ya compara en minúsculas, así que ese bucle es toda la normalización
|
||||||
|
> necesaria.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Controllers
|
||||||
|
|
||||||
|
Solo declaran el recurso. Toda la lógica REST vive en `CrudController`.
|
||||||
|
|
||||||
|
```php
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Http;
|
||||||
|
|
||||||
|
use App\Gateway\ArticuloGateway;
|
||||||
|
use Camelia\Controllers\CrudController;
|
||||||
|
|
||||||
|
final class ArticuloController extends CrudController
|
||||||
|
{
|
||||||
|
public function __construct(ArticuloGateway $gateway)
|
||||||
|
{
|
||||||
|
parent::__construct($gateway, 'articulos');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```php
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Http;
|
||||||
|
|
||||||
|
use App\Gateway\ClienteGateway;
|
||||||
|
use Camelia\Controllers\CrudController;
|
||||||
|
|
||||||
|
final class ClienteController extends CrudController
|
||||||
|
{
|
||||||
|
public function __construct(ClienteGateway $gateway)
|
||||||
|
{
|
||||||
|
parent::__construct($gateway, 'clientes');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Adaptadores de ORM
|
||||||
|
|
||||||
|
Aquí vive el acoplamiento, y solo aquí.
|
||||||
|
|
||||||
|
```php
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Gateway;
|
||||||
|
|
||||||
|
use Camelia\Controllers\ResourceGateway;
|
||||||
|
use Camelia\Orm\Model;
|
||||||
|
use Camelia\Orm\Repository;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @template T of Model
|
||||||
|
*/
|
||||||
|
abstract class OrmGateway implements ResourceGateway
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param Repository<T> $repository
|
||||||
|
*/
|
||||||
|
public function __construct(protected readonly Repository $repository) {}
|
||||||
|
|
||||||
|
public function findAll(array $query = []): array
|
||||||
|
{
|
||||||
|
$perPage = max(1, min(1000, (int) ($query['per_page'] ?? 20)));
|
||||||
|
$page = max(1, (int) ($query['page'] ?? 1));
|
||||||
|
|
||||||
|
$items = $this->repository->find(
|
||||||
|
order: $this->orderFrom($query),
|
||||||
|
limit: $perPage,
|
||||||
|
offset: ($page - 1) * $perPage,
|
||||||
|
);
|
||||||
|
|
||||||
|
return array_map($this->toArray(...), $items);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function find(int|string $id): ?array
|
||||||
|
{
|
||||||
|
$model = $this->repository->findByPk($id);
|
||||||
|
|
||||||
|
return $model === null ? null : $this->toArray($model);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function create(array $values): array
|
||||||
|
{
|
||||||
|
return $this->toArray($this->repository->create($values));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function update(int|string $id, array $values): ?array
|
||||||
|
{
|
||||||
|
$model = $this->repository->findByPk($id);
|
||||||
|
|
||||||
|
if ($model === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$model->assign($values);
|
||||||
|
$this->repository->save($model);
|
||||||
|
|
||||||
|
return $this->toArray($model);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function delete(int|string $id): bool
|
||||||
|
{
|
||||||
|
return $this->repository->remove($id) > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function count(array $query = []): ?int
|
||||||
|
{
|
||||||
|
return $this->repository->count();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
protected function toArray(Model $model): array
|
||||||
|
{
|
||||||
|
return $model->toArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Traduce `sort`/`order` del query string al formato del ORM.
|
||||||
|
*
|
||||||
|
* @param array<string, mixed> $query
|
||||||
|
* @return list<array{0: string, 1: 'ASC'|'DESC'}>
|
||||||
|
*/
|
||||||
|
private function orderFrom(array $query): array
|
||||||
|
{
|
||||||
|
$sort = (string) ($query['sort'] ?? '');
|
||||||
|
$order = strtoupper((string) ($query['order'] ?? 'ASC'));
|
||||||
|
|
||||||
|
if ($sort === '') {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return [[$sort, $order === 'DESC' ? 'DESC' : 'ASC']];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```php
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Gateway;
|
||||||
|
|
||||||
|
final class ArticuloGateway extends OrmGateway {}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Manejo de duplicados
|
||||||
|
|
||||||
|
El ORM lanza `DuplicateKeyException`; la API responde 409. El mapeo vive en un controller, no en la
|
||||||
|
librería.
|
||||||
|
|
||||||
|
```php
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Http;
|
||||||
|
|
||||||
|
use App\Gateway\ArticuloGateway;
|
||||||
|
use Camelia\Controllers\CrudController;
|
||||||
|
use Camelia\Controllers\Exception\Conflict;
|
||||||
|
use Camelia\Controllers\Request;
|
||||||
|
use Camelia\Controllers\Response;
|
||||||
|
use Camelia\Orm\Exception\DuplicateKeyException;
|
||||||
|
|
||||||
|
final class ArticuloController extends CrudController
|
||||||
|
{
|
||||||
|
public function __construct(ArticuloGateway $gateway)
|
||||||
|
{
|
||||||
|
parent::__construct($gateway, 'articulos');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(Request $request): Response
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
return parent::store($request);
|
||||||
|
} catch (DuplicateKeyException) {
|
||||||
|
return $this->error(new Conflict('An articulo with that code already exists.'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Test de la API completa
|
||||||
|
|
||||||
|
```php
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Tests;
|
||||||
|
|
||||||
|
use Camelia\Controllers\JsonRequest;
|
||||||
|
use Camelia\Controllers\ResourceGateway;
|
||||||
|
use Camelia\Controllers\Response;
|
||||||
|
use Camelia\Controllers\Router;
|
||||||
|
use Camelia\Controllers\Security\BearerAuth;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
final class ApiTest extends TestCase
|
||||||
|
{
|
||||||
|
private function router(ResourceGateway $gateway, bool $authenticated = true): Router
|
||||||
|
{
|
||||||
|
$router = (new Router())->withMiddleware(
|
||||||
|
new BearerAuth(static fn (string $token): ?array => $authenticated ? ['id' => 1] : null),
|
||||||
|
);
|
||||||
|
|
||||||
|
$router->get('/articulos', new ArticuloController($gateway));
|
||||||
|
$router->get('/articulos/{id}', new ArticuloController($gateway));
|
||||||
|
$router->post('/articulos', new ArticuloController($gateway));
|
||||||
|
$router->delete('/articulos/{id}', new ArticuloController($gateway));
|
||||||
|
|
||||||
|
return $router;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testFullCrudFlow(): void
|
||||||
|
{
|
||||||
|
$gateway = new InMemoryGateway();
|
||||||
|
$router = $this->router($gateway);
|
||||||
|
|
||||||
|
// POST crea
|
||||||
|
$created = $router->dispatch(new JsonRequest(
|
||||||
|
method: 'POST',
|
||||||
|
path: '/articulos',
|
||||||
|
body: ['nombre' => 'Taladro', 'precio' => 120.5],
|
||||||
|
headers: ['authorization' => 'Bearer token'],
|
||||||
|
));
|
||||||
|
|
||||||
|
self::assertSame(201, $created->status());
|
||||||
|
self::assertSame('/articulos/1', $created->headers()['Location']);
|
||||||
|
self::assertSame('Taladro', $created->body()['nombre']);
|
||||||
|
|
||||||
|
// GET lo lee
|
||||||
|
$shown = $router->dispatch(new JsonRequest(
|
||||||
|
path: '/articulos/1',
|
||||||
|
headers: ['authorization' => 'Bearer token'],
|
||||||
|
));
|
||||||
|
|
||||||
|
self::assertSame(200, $shown->status());
|
||||||
|
self::assertSame(120.5, $shown->body()['precio']);
|
||||||
|
|
||||||
|
// GET lista
|
||||||
|
$listed = $router->dispatch(new JsonRequest(
|
||||||
|
path: '/articulos',
|
||||||
|
headers: ['authorization' => 'Bearer token'],
|
||||||
|
));
|
||||||
|
|
||||||
|
self::assertSame(1, $listed->body()['total']);
|
||||||
|
self::assertSame(20, $listed->body()['per_page']);
|
||||||
|
|
||||||
|
// DELETE borra
|
||||||
|
$deleted = $router->dispatch(new JsonRequest(
|
||||||
|
method: 'DELETE',
|
||||||
|
path: '/articulos/1',
|
||||||
|
headers: ['authorization' => 'Bearer token'],
|
||||||
|
));
|
||||||
|
|
||||||
|
self::assertSame(204, $deleted->status());
|
||||||
|
|
||||||
|
// Ya no existe
|
||||||
|
$missing = $router->dispatch(new JsonRequest(
|
||||||
|
path: '/articulos/1',
|
||||||
|
headers: ['authorization' => 'Bearer token'],
|
||||||
|
));
|
||||||
|
|
||||||
|
self::assertSame(404, $missing->status());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testRejectsAnonymous(): void
|
||||||
|
{
|
||||||
|
$router = $this->router(new InMemoryGateway(), authenticated: false);
|
||||||
|
|
||||||
|
$response = $router->dispatch(new JsonRequest(path: '/articulos'));
|
||||||
|
|
||||||
|
self::assertSame(401, $response->status());
|
||||||
|
self::assertSame('unauthorized', $response->body()['code']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testPaginationClampsPerPage(): void
|
||||||
|
{
|
||||||
|
$gateway = new InMemoryGateway();
|
||||||
|
|
||||||
|
for ($i = 1; $i <= 30; ++$i) {
|
||||||
|
$gateway->create(['nombre' => 'Articulo ' . $i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$router = $this->router($gateway);
|
||||||
|
|
||||||
|
$response = $router->dispatch(new JsonRequest(
|
||||||
|
path: '/articulos',
|
||||||
|
query: ['page' => '2', 'per_page' => '10'],
|
||||||
|
headers: ['authorization' => 'Bearer token'],
|
||||||
|
));
|
||||||
|
|
||||||
|
self::assertSame(2, $response->body()['page']);
|
||||||
|
self::assertSame(10, $response->body()['per_page']);
|
||||||
|
self::assertSame(30, $response->body()['total']);
|
||||||
|
self::assertSame(3, $response->body()['total_pages']);
|
||||||
|
self::assertTrue($response->body()['has_next']);
|
||||||
|
self::assertTrue($response->body()['has_prev']);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final class InMemoryGateway implements ResourceGateway
|
||||||
|
{
|
||||||
|
/** @var array<int, array<string, mixed>> */
|
||||||
|
private array $records = [];
|
||||||
|
|
||||||
|
public function findAll(array $query = []): array
|
||||||
|
{
|
||||||
|
return array_values($this->records);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function find(int|string $id): ?array
|
||||||
|
{
|
||||||
|
return $this->records[(int) $id] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function create(array $values): array
|
||||||
|
{
|
||||||
|
$id = count($this->records) + 1;
|
||||||
|
$this->records[$id] = ['id' => $id] + $values;
|
||||||
|
|
||||||
|
return $this->records[$id];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function update(int|string $id, array $values): ?array
|
||||||
|
{
|
||||||
|
if (!isset($this->records[(int) $id])) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->records[(int) $id] = ['id' => (int) $id] + $values;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function delete(int|string $id): bool
|
||||||
|
{
|
||||||
|
if (!isset($this->records[(int) $id])) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
unset($this->records[(int) $id]);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function count(array $query = []): ?int
|
||||||
|
{
|
||||||
|
return count($this->records);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Recetas sueltas
|
||||||
|
|
||||||
|
### Rate limit por usuario autenticado, no por IP
|
||||||
|
|
||||||
|
```php
|
||||||
|
new RateLimit(
|
||||||
|
limit: 1000,
|
||||||
|
windowSeconds: 3600,
|
||||||
|
keyResolver: static function (Request $request): string {
|
||||||
|
$user = $request->attribute('user');
|
||||||
|
|
||||||
|
return is_array($user) ? 'user:' . (string) $user['id'] : 'anon';
|
||||||
|
},
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
Va **después** de `BearerAuth` en el pipeline; si va antes, todavía no hay identidad.
|
||||||
|
|
||||||
|
### CORS estricto para producción
|
||||||
|
|
||||||
|
```php
|
||||||
|
new Cors(
|
||||||
|
allowedOrigins: ['https://erp.midominio.com'],
|
||||||
|
allowedMethods: ['GET', 'POST', 'PUT', 'DELETE'],
|
||||||
|
allowedHeaders: ['Content-Type', 'Authorization'],
|
||||||
|
allowCredentials: true,
|
||||||
|
maxAge: 3600,
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Un middleware que exige un header de trazabilidad
|
||||||
|
|
||||||
|
```php
|
||||||
|
final readonly class RequireTraceId implements Middleware
|
||||||
|
{
|
||||||
|
public function process(Request $request, callable $next): Response
|
||||||
|
{
|
||||||
|
$trace = $request->header('X-Trace-Id');
|
||||||
|
|
||||||
|
if ($trace === null || $trace === '') {
|
||||||
|
return new Response(
|
||||||
|
['error' => ['code' => 'bad_request', 'message' => 'X-Trace-Id is required.']],
|
||||||
|
400,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $next($request)->withHeader('X-Trace-Id', $trace);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Por dónde seguir
|
||||||
|
|
||||||
|
- **[GUIA-PROGRAMADOR.md](GUIA-PROGRAMADOR.md)** — el recorrido completo, con trampas.
|
||||||
|
- **[ARQUITECTURA.md](ARQUITECTURA.md)** — el porqué de cada pieza.
|
||||||
@@ -0,0 +1,911 @@
|
|||||||
|
# camelia/controllers — Guía del programador
|
||||||
|
|
||||||
|
## Índice
|
||||||
|
|
||||||
|
1. [Instalación y arranque](#1-instalación-y-arranque)
|
||||||
|
2. [El request: nunca superglobales](#2-el-request-nunca-superglobales)
|
||||||
|
3. [La respuesta: nunca echo](#3-la-respuesta-nunca-echo)
|
||||||
|
4. [Rutas](#4-rutas)
|
||||||
|
5. [Tu primer controller](#5-tu-primer-controller)
|
||||||
|
6. [CRUD completo en una clase](#6-crud-completo-en-una-clase)
|
||||||
|
7. [El puerto ResourceGateway](#7-el-puerto-resourcegateway)
|
||||||
|
8. [Errores y códigos HTTP](#8-errores-y-códigos-http)
|
||||||
|
9. [Middlewares](#9-middlewares)
|
||||||
|
10. [Seguridad](#10-seguridad)
|
||||||
|
11. [Testing](#11-testing)
|
||||||
|
12. [Recetas frecuentes](#12-recetas-frecuentes)
|
||||||
|
13. [Trampas y errores comunes](#13-trampas-y-errores-comunes)
|
||||||
|
14. [Referencia de API](#14-referencia-de-api)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Instalación y arranque
|
||||||
|
|
||||||
|
```bash
|
||||||
|
composer require camelia/controllers
|
||||||
|
```
|
||||||
|
|
||||||
|
El punto de entrada es un `index.php` que traduce el entorno web a un `Request`, despacha, y emite
|
||||||
|
la `Response`. Esas dos traducciones son **tuyas**: la librería no toca `$_SERVER`.
|
||||||
|
|
||||||
|
```php
|
||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
require __DIR__ . '/vendor/autoload.php';
|
||||||
|
|
||||||
|
use Camelia\Controllers\{JsonRequest, Router, Response};
|
||||||
|
|
||||||
|
$router = new Router();
|
||||||
|
$router->get('/salud', static fn (): Response => new Response(['status' => 'ok']));
|
||||||
|
|
||||||
|
$request = new JsonRequest(
|
||||||
|
method: $_SERVER['REQUEST_METHOD'] ?? 'GET',
|
||||||
|
path: parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/',
|
||||||
|
query: $_GET,
|
||||||
|
body: json_decode(file_get_contents('php://input') ?: '{}', true) ?: [],
|
||||||
|
);
|
||||||
|
|
||||||
|
$response = $router->dispatch($request);
|
||||||
|
|
||||||
|
http_response_code($response->status());
|
||||||
|
|
||||||
|
foreach ($response->headers() as $name => $value) {
|
||||||
|
header($name . ': ' . $value);
|
||||||
|
}
|
||||||
|
|
||||||
|
echo $response->toJson();
|
||||||
|
```
|
||||||
|
|
||||||
|
> El `body` lo decodificas tú. `JsonRequest` recibe un array ya decodificado: así un JSON inválido se
|
||||||
|
> rechaza donde corresponde, no dentro de la librería.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. El request: nunca superglobales
|
||||||
|
|
||||||
|
`Request` es una interfaz. Su implementación `JsonRequest` guarda arrays y es **inmutable**.
|
||||||
|
|
||||||
|
```php
|
||||||
|
$request = new JsonRequest(
|
||||||
|
method: 'GET',
|
||||||
|
path: '/articulos',
|
||||||
|
query: ['page' => '2', 'q' => 'taladro'],
|
||||||
|
body: [],
|
||||||
|
headers: ['authorization' => 'Bearer abc'],
|
||||||
|
);
|
||||||
|
|
||||||
|
$request->method(); // 'GET'
|
||||||
|
$request->path(); // '/articulos'
|
||||||
|
$request->query('page'); // '2'
|
||||||
|
$request->query('missing'); // null
|
||||||
|
$request->query('missing', 20); // 20
|
||||||
|
$request->header('Authorization'); // 'Bearer abc' (case-insensitive)
|
||||||
|
$request->attribute('id'); // null hasta que el router lo puebla
|
||||||
|
```
|
||||||
|
|
||||||
|
`withAttribute()` devuelve **copia**, no muta:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$a = new JsonRequest();
|
||||||
|
$b = $a->withAttribute('id', '7');
|
||||||
|
|
||||||
|
$a->attribute('id'); // null
|
||||||
|
$b->attribute('id'); // '7'
|
||||||
|
```
|
||||||
|
|
||||||
|
### Por qué no superglobales
|
||||||
|
|
||||||
|
Es la única forma de testear sin servidor. Un test construye el `JsonRequest` y llama a
|
||||||
|
`dispatch()`. Cero red, cero `php -S`, cero mocks del entorno.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. La respuesta: nunca echo
|
||||||
|
|
||||||
|
`Response` es inmutable y **no emite nada**. Guardarla y devolverla es todo lo que hace un handler.
|
||||||
|
|
||||||
|
```php
|
||||||
|
use Camelia\Controllers\Response;
|
||||||
|
|
||||||
|
new Response(['id' => 1], 201);
|
||||||
|
new Response(['error' => 'x'], 404, ['X-Trace' => 'abc']);
|
||||||
|
Response::noContent(); // 204, cuerpo null
|
||||||
|
|
||||||
|
$r = new Response(['ok' => true]);
|
||||||
|
$r->status(); // 200
|
||||||
|
$r->body(); // ['ok' => true]
|
||||||
|
$r->isSuccessful(); // true
|
||||||
|
$r->toJson(); // '{"ok":true}'
|
||||||
|
$r->withHeader('X-Foo', 'bar'); // copia con la cabecera
|
||||||
|
```
|
||||||
|
|
||||||
|
`toJson()` aplica `JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES`. Un cuerpo `null` serializa a
|
||||||
|
cadena vacía. Si el JSON no se puede codificar, lanza `JsonException` (`JSON_THROW_ON_ERROR`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Rutas
|
||||||
|
|
||||||
|
```php
|
||||||
|
$router = new Router();
|
||||||
|
|
||||||
|
$router->get('/articulos', $controller);
|
||||||
|
$router->post('/articulos', $controller);
|
||||||
|
$router->get('/articulos/{id}', $controller);
|
||||||
|
$router->put('/articulos/{id}', $controller);
|
||||||
|
$router->patch('/articulos/{id}', $controller);
|
||||||
|
$router->delete('/articulos/{id}', $controller);
|
||||||
|
$router->add('HEAD', '/articulos', $controller); // cualquier verbo
|
||||||
|
```
|
||||||
|
|
||||||
|
Los métodos son **encadenables**: cada uno devuelve el mismo router.
|
||||||
|
|
||||||
|
### Parámetros
|
||||||
|
|
||||||
|
`{id}` captura un segmento (sin `/`). Se exponen como atributos del request:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$router->get('/facturas/{facturaId}/detalles/{detalleId}',
|
||||||
|
static fn (Request $r): Response => new Response([
|
||||||
|
'factura' => $r->attribute('facturaId'),
|
||||||
|
'detalle' => $r->attribute('detalleId'),
|
||||||
|
]));
|
||||||
|
```
|
||||||
|
|
||||||
|
```php
|
||||||
|
$router->dispatch(new JsonRequest(path: '/facturas/3/detalles/9'));
|
||||||
|
// {"factura":"3","detalle":"9"}
|
||||||
|
```
|
||||||
|
|
||||||
|
Los valores son **siempre string**. Convertir a `int` es de tu handler.
|
||||||
|
|
||||||
|
### Resolución y errores
|
||||||
|
|
||||||
|
| Situación | Respuesta |
|
||||||
|
|---|---|
|
||||||
|
| Ruta y método coinciden | El handler |
|
||||||
|
| Ninguna ruta con ese path | 404 `not_found` |
|
||||||
|
| El path existe pero con otro método | 405 `method_not_allowed` + `Allow` |
|
||||||
|
| HEAD pedida donde hay GET | 405 con `Allow: GET, HEAD` |
|
||||||
|
|
||||||
|
El 405 nunca aparece si el path no existe: solo cuando el recurso está ahí y el verbo no.
|
||||||
|
|
||||||
|
### Handlers: controller o closure
|
||||||
|
|
||||||
|
```php
|
||||||
|
$router->get('/a', $controller); // llama $controller->render($request)
|
||||||
|
$router->get('/b', static fn (Request $r): Response => ...); // se invoca directo
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Tu primer controller
|
||||||
|
|
||||||
|
`Controller` es abstracta. Aporta helpers de respuesta; `render()` es lo único obligatorio.
|
||||||
|
|
||||||
|
```php
|
||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Http;
|
||||||
|
|
||||||
|
use Camelia\Controllers\{Controller, Request, Response};
|
||||||
|
use Camelia\Controllers\Exception\NotFound;
|
||||||
|
|
||||||
|
final class HealthController extends Controller
|
||||||
|
{
|
||||||
|
public function render(Request $request): Response
|
||||||
|
{
|
||||||
|
return match ($request->path()) {
|
||||||
|
'/salud' => $this->json(['status' => 'ok']),
|
||||||
|
default => $this->error(new NotFound('Unknown health route.')),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Helpers disponibles
|
||||||
|
|
||||||
|
```php
|
||||||
|
$this->json(mixed $data, int $status = 200, array $headers = []);
|
||||||
|
$this->page(array $items, int $page, int $perPage, int $total);
|
||||||
|
$this->created(mixed $data, string $location); // 201 + Location
|
||||||
|
$this->noContent(); // 204
|
||||||
|
$this->error(HttpError $error); // status + forma JSON
|
||||||
|
$this->notFound('mensaje'); // 404
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. CRUD completo en una clase
|
||||||
|
|
||||||
|
`CrudController` implementa las cinco acciones REST. No tenés que escribir nada más que el nombre
|
||||||
|
del recurso.
|
||||||
|
|
||||||
|
```php
|
||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Http;
|
||||||
|
|
||||||
|
use Camelia\Controllers\CrudController;
|
||||||
|
|
||||||
|
final class ArticuloController extends CrudController
|
||||||
|
{
|
||||||
|
public function __construct(ArticuloGateway $gateway)
|
||||||
|
{
|
||||||
|
parent::__construct($gateway, 'articulos');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```php
|
||||||
|
$router->get('/articulos', $articulo);
|
||||||
|
$router->post('/articulos', $articulo);
|
||||||
|
$router->get('/articulos/{id}', $articulo);
|
||||||
|
$router->put('/articulos/{id}', $articulo);
|
||||||
|
$router->delete('/articulos/{id}', $articulo);
|
||||||
|
```
|
||||||
|
|
||||||
|
| Acción | Método | Ruta | Respuesta |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `index` | GET | `/articulos` | 200 + página |
|
||||||
|
| `show` | GET | `/articulos/{id}` | 200 / 404 |
|
||||||
|
| `store` | POST | `/articulos` | 201 + `Location` |
|
||||||
|
| `update` | PUT/PATCH | `/articulos/{id}` | 200 / 404 |
|
||||||
|
| `destroy` | DELETE | `/articulos/{id}` | 204 / 404 |
|
||||||
|
|
||||||
|
### Paginación
|
||||||
|
|
||||||
|
`index` lee `page` y `per_page` del query string. `page` inválido cae a 1; `per_page` se recorta a
|
||||||
|
`1..1000` (default 20).
|
||||||
|
|
||||||
|
```json
|
||||||
|
GET /articulos?page=2&per_page=10
|
||||||
|
{
|
||||||
|
"items": [ ... ],
|
||||||
|
"page": 2,
|
||||||
|
"per_page": 10,
|
||||||
|
"total": 43,
|
||||||
|
"total_pages": 5,
|
||||||
|
"has_next": true,
|
||||||
|
"has_prev": true
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Misma forma que `Camelia\Orm\Pagination\Page::toArray()`, para que la app no traduzca nada.
|
||||||
|
|
||||||
|
### Filtros
|
||||||
|
|
||||||
|
`index` reenvía `sort`, `order` y `q` al gateway como parte del `$query`:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$gateway->findAll(['sort' => 'nombre', 'order' => 'asc', 'q' => 'taladro', 'page' => 2, 'per_page' => 20]);
|
||||||
|
```
|
||||||
|
|
||||||
|
Filtrar por otras columnas es de tu gateway, que recibe el `$query` completo.
|
||||||
|
|
||||||
|
### Sobrescribir una acción
|
||||||
|
|
||||||
|
```php
|
||||||
|
final class ArticuloController extends CrudController
|
||||||
|
{
|
||||||
|
public function __construct(ArticuloGateway $gateway)
|
||||||
|
{
|
||||||
|
parent::__construct($gateway, 'articulos');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(Request $request): Response
|
||||||
|
{
|
||||||
|
if (!isset($request->body()['nombre'])) {
|
||||||
|
return $this->error(new ValidationFailed(['nombre' => ['Required.']]));
|
||||||
|
}
|
||||||
|
|
||||||
|
return parent::store($request);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. El puerto ResourceGateway
|
||||||
|
|
||||||
|
La librería **no** conoce tu base de datos. Todo pasa por esta interfaz:
|
||||||
|
|
||||||
|
```php
|
||||||
|
interface ResourceGateway
|
||||||
|
{
|
||||||
|
public function findAll(array $query = []): array; // list<array>
|
||||||
|
public function find(int|string $id): ?array; // null si no existe
|
||||||
|
public function create(array $values): array;
|
||||||
|
public function update(int|string $id, array $values): ?array; // null si no existe
|
||||||
|
public function delete(int|string $id): bool; // true si borró
|
||||||
|
public function count(array $query = []): ?int; // null si no sabe contar
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Contrato
|
||||||
|
|
||||||
|
- Los registros son **arrays asociativos**. Serializar es del controller.
|
||||||
|
- `find` y `update` devuelven `null` cuando no existe. **No lances excepciones HTTP aquí.**
|
||||||
|
- `delete` devuelve `bool`. `false` → 404.
|
||||||
|
- `count` puede devolver `null`; el CRUD lo interpreta como 0.
|
||||||
|
|
||||||
|
### Adaptador desde `camelia/orm`
|
||||||
|
|
||||||
|
```php
|
||||||
|
final class ArticuloGateway implements ResourceGateway
|
||||||
|
{
|
||||||
|
public function __construct(private readonly Repository $repository) {}
|
||||||
|
|
||||||
|
public function findAll(array $query = []): array
|
||||||
|
{
|
||||||
|
$items = $this->repository->find(
|
||||||
|
order: [['nombre', 'ASC']],
|
||||||
|
limit: (int) ($query['per_page'] ?? 20),
|
||||||
|
offset: (((int) ($query['page'] ?? 1)) - 1) * (int) ($query['per_page'] ?? 20),
|
||||||
|
);
|
||||||
|
|
||||||
|
return array_map(static fn (Articulo $a): array => $a->toArray(), $items);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function find(int|string $id): ?array
|
||||||
|
{
|
||||||
|
return $this->repository->findByPk($id)?->toArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function create(array $values): array
|
||||||
|
{
|
||||||
|
return $this->repository->create($values)->toArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function update(int|string $id, array $values): ?array
|
||||||
|
{
|
||||||
|
$model = $this->repository->findByPk($id);
|
||||||
|
|
||||||
|
if ($model === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$model->assign($values);
|
||||||
|
$this->repository->save($model);
|
||||||
|
|
||||||
|
return $model->toArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function delete(int|string $id): bool
|
||||||
|
{
|
||||||
|
return $this->repository->remove($id) > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function count(array $query = []): ?int
|
||||||
|
{
|
||||||
|
return $this->repository->count();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
> Este acoplamiento vive en **tu** app, no en la librería. `camelia/controllers` no declara
|
||||||
|
> `camelia/orm` como dependencia.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Errores y códigos HTTP
|
||||||
|
|
||||||
|
Toda falla es un `HttpError` con status y código estable.
|
||||||
|
|
||||||
|
```php
|
||||||
|
use Camelia\Controllers\Exception\{NotFound, BadRequest, Conflict, ValidationFailed};
|
||||||
|
|
||||||
|
throw new NotFound('Articulo 7 does not exist.');
|
||||||
|
throw NotFound::resource('articulos', 7); // 'Articulos 7 does not exist.'
|
||||||
|
throw NotFound::route('/nada'); // 'No route matches "/nada".'
|
||||||
|
throw new ValidationFailed(['nombre' => ['Required.']]);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Forma JSON
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "error": { "code": "not_found", "message": "Articulo 7 does not exist." } }
|
||||||
|
```
|
||||||
|
|
||||||
|
### Tabla completa
|
||||||
|
|
||||||
|
| Clase | Status | `code` | Extra |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `BadRequest` | 400 | `bad_request` | — |
|
||||||
|
| `Unauthorized` | 401 | `unauthorized` | `WWW-Authenticate: Bearer` |
|
||||||
|
| `NotFound` | 404 | `not_found` | — |
|
||||||
|
| `MethodNotAllowed` | 405 | `method_not_allowed` | `Allow` |
|
||||||
|
| `Conflict` | 409 | `conflict` | — |
|
||||||
|
| `ValidationFailed` | 422 | `validation_failed` | `errors: {campo: [mensajes]}` |
|
||||||
|
| `ServerError` | 500 | `server_error` | mensaje genérico |
|
||||||
|
|
||||||
|
### Cómo se convierten
|
||||||
|
|
||||||
|
`Router::dispatch()` captura **todo**:
|
||||||
|
|
||||||
|
- `HttpError` → su status y su forma.
|
||||||
|
- `Throwable` cualquiera → `ServerError` (500) con mensaje genérico. **El detalle interno nunca llega
|
||||||
|
al cliente.**
|
||||||
|
|
||||||
|
Si un handler lanza, el cliente ve 500 limpio y vos ves la excepción en tu log.
|
||||||
|
|
||||||
|
### Códigos sin clase propia
|
||||||
|
|
||||||
|
| Status | Cuándo |
|
||||||
|
|---|---|
|
||||||
|
| 406 `not_acceptable` | `ContentNegotiation` y el `Accept` no casa |
|
||||||
|
| 429 `too_many_requests` | `RateLimit` excedido |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Middlewares
|
||||||
|
|
||||||
|
Un middleware envuelve al handler. Delega con `$next($request)` o corta devolviendo un `Response`.
|
||||||
|
|
||||||
|
```php
|
||||||
|
use Camelia\Controllers\{Middleware, Request, Response};
|
||||||
|
|
||||||
|
final readonly class Timing implements Middleware
|
||||||
|
{
|
||||||
|
public function process(Request $request, callable $next): Response
|
||||||
|
{
|
||||||
|
$start = hrtime(true);
|
||||||
|
$response = $next($request);
|
||||||
|
$elapsed = (hrtime(true) - $start) / 1_000_000;
|
||||||
|
|
||||||
|
return $response->withHeader('X-Elapsed-Ms', (string) round($elapsed, 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Registro
|
||||||
|
|
||||||
|
```php
|
||||||
|
$router = (new Router())
|
||||||
|
->withMiddleware(new ContentNegotiation())
|
||||||
|
->withMiddleware(new Cors())
|
||||||
|
->withMiddleware(new RateLimit(limit: 120));
|
||||||
|
```
|
||||||
|
|
||||||
|
`withMiddleware()` devuelve **copia**. El router original queda intacto:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$public = new Router();
|
||||||
|
$private = $public->withMiddleware(new BearerAuth($verify));
|
||||||
|
|
||||||
|
$public->pipeline()->isEmpty(); // true
|
||||||
|
```
|
||||||
|
|
||||||
|
### Orden
|
||||||
|
|
||||||
|
Se ejecutan de fuera hacia dentro: el primero añadido es el más externo.
|
||||||
|
|
||||||
|
```
|
||||||
|
ContentNegotiation → Cors → RateLimit → BearerAuth → RequireRole → handler
|
||||||
|
```
|
||||||
|
|
||||||
|
Errores de orden que cuestan caro:
|
||||||
|
|
||||||
|
- `Cors` **antes** de `BearerAuth`, o el preflight `OPTIONS` se come un 401.
|
||||||
|
- `ContentNegotiation` **primero**, o un 406 sale sin cabeceras CORS y el navegador no lo puede leer.
|
||||||
|
|
||||||
|
### `Pipeline` directo
|
||||||
|
|
||||||
|
Sin router:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$pipeline = new Pipeline([new Cors(), new RateLimit(limit: 10)]);
|
||||||
|
$response = $pipeline->process($request, $miHandler);
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Seguridad
|
||||||
|
|
||||||
|
### `BearerAuth`
|
||||||
|
|
||||||
|
```php
|
||||||
|
use Camelia\Controllers\Security\BearerAuth;
|
||||||
|
|
||||||
|
$auth = new BearerAuth(static function (string $token): ?array {
|
||||||
|
// Devolvé la identidad, o null si el token es inválido.
|
||||||
|
return $jwt->verify($token); // ['id' => 7, 'roles' => ['admin']]
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
- Sin cabecera, esquema distinto o token inválido → **401**.
|
||||||
|
- Éxito → la identidad queda en `$request->attribute('user')`.
|
||||||
|
- La verificación del token es **tuya**. La librería no implementa JWT ni criptografía.
|
||||||
|
|
||||||
|
### `RequireRole`
|
||||||
|
|
||||||
|
```php
|
||||||
|
use Camelia\Controllers\Security\RequireRole;
|
||||||
|
|
||||||
|
new RequireRole(['admin', 'gerente']); // cualquiera de los dos
|
||||||
|
```
|
||||||
|
|
||||||
|
Lee roles de `$identity['roles']` (lista) o `$identity['role']` (string único).
|
||||||
|
|
||||||
|
**Falla cerrado**: sin identidad, identidad no-array o roles malformados → 401. Nunca 200.
|
||||||
|
|
||||||
|
### `RateLimit`
|
||||||
|
|
||||||
|
```php
|
||||||
|
new RateLimit(limit: 60, windowSeconds: 60);
|
||||||
|
```
|
||||||
|
|
||||||
|
- Excedido → **429** + `Retry-After` en segundos.
|
||||||
|
- Toda respuesta lleva `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` (epoch).
|
||||||
|
- Clave: atributo `client_ip` del request. Sin él, un bucket compartido `anonymous`.
|
||||||
|
|
||||||
|
```php
|
||||||
|
// clave personalizada
|
||||||
|
new RateLimit(limit: 10, keyResolver: static fn (Request $r): string =>
|
||||||
|
(string) $r->attribute('user')['id'] ?? 'anon');
|
||||||
|
```
|
||||||
|
|
||||||
|
> **El contador vive en memoria del proceso.** Detrás de N workers, el límite efectivo es N×. Es
|
||||||
|
> deliberado: añadir Redis rompería la regla de cero dependencias.
|
||||||
|
|
||||||
|
### `Cors`
|
||||||
|
|
||||||
|
```php
|
||||||
|
new Cors(
|
||||||
|
allowedOrigins: ['https://app.midominio.com'],
|
||||||
|
allowedMethods: ['GET', 'POST', 'PUT', 'DELETE'],
|
||||||
|
allowedHeaders: ['Content-Type', 'Authorization'],
|
||||||
|
allowCredentials: true,
|
||||||
|
maxAge: 86400,
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
- `OPTIONS` responde **204** sin llegar al handler.
|
||||||
|
- Origen no permitido → **no** se envía `Access-Control-Allow-Origin` (el navegador bloquea).
|
||||||
|
- `*` + `allowCredentials: true` es inválido: se repite el origen exacto en su lugar.
|
||||||
|
- Siempre envía `Vary: Origin`.
|
||||||
|
|
||||||
|
### `Logging`
|
||||||
|
|
||||||
|
```php
|
||||||
|
use Camelia\Controllers\Middleware\Logging;
|
||||||
|
|
||||||
|
new Logging(static function (string $level, string $message, array $context): void {
|
||||||
|
error_log(sprintf('[%s] %s', $level, $message));
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
Nivel según el status: `5xx` → `error`, `4xx` → `warning`, resto → `info`.
|
||||||
|
|
||||||
|
Conectar un PSR-3:
|
||||||
|
|
||||||
|
```php
|
||||||
|
new Logging(static fn (string $level, string $message, array $context): void =>
|
||||||
|
$logger->log($level, $message, $context));
|
||||||
|
```
|
||||||
|
|
||||||
|
### `ContentNegotiation`
|
||||||
|
|
||||||
|
```php
|
||||||
|
new ContentNegotiation();
|
||||||
|
```
|
||||||
|
|
||||||
|
- `Accept` que no casa con JSON → **406** `not_acceptable`.
|
||||||
|
- `Accept` ausente → se acepta todo (RFC 9110).
|
||||||
|
- `q=0` no cuenta como aceptado.
|
||||||
|
- Añade `Content-Type: application/json; charset=utf-8` si falta.
|
||||||
|
|
||||||
|
**No comprime.** `Response` es inmutable y el cuerpo lo serializa el adaptador; un `gzencode()`
|
||||||
|
aquí duplicaría el trabajo y rompería `Content-Length`. Eso es del servidor.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11. Testing
|
||||||
|
|
||||||
|
La librería está diseñada para tests sin servidor, sin base y sin red.
|
||||||
|
|
||||||
|
### Gateway en memoria
|
||||||
|
|
||||||
|
```php
|
||||||
|
use Camelia\Controllers\ResourceGateway;
|
||||||
|
|
||||||
|
final class ArrayGateway implements ResourceGateway
|
||||||
|
{
|
||||||
|
public function __construct(private array $records = []) {}
|
||||||
|
|
||||||
|
public function findAll(array $query = []): array { return array_values($this->records); }
|
||||||
|
public function find(int|string $id): ?array { return $this->records[$id] ?? null; }
|
||||||
|
|
||||||
|
public function create(array $values): array
|
||||||
|
{
|
||||||
|
$id = count($this->records) + 1;
|
||||||
|
$this->records[$id] = ['id' => $id] + $values;
|
||||||
|
|
||||||
|
return $this->records[$id];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function update(int|string $id, array $values): ?array
|
||||||
|
{
|
||||||
|
if (!isset($this->records[$id])) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->records[$id] = ['id' => $id] + $values;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function delete(int|string $id): bool
|
||||||
|
{
|
||||||
|
unset($this->records[$id]);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function count(array $query = []): ?int { return count($this->records); }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Test de un endpoint
|
||||||
|
|
||||||
|
```php
|
||||||
|
use Camelia\Controllers\{JsonRequest, Router};
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
final class ArticuloEndpointTest extends TestCase
|
||||||
|
{
|
||||||
|
public function testShowReturnsRecord(): void
|
||||||
|
{
|
||||||
|
$gateway = new ArrayGateway([1 => ['id' => 1, 'nombre' => 'Taladro']]);
|
||||||
|
$router = new Router();
|
||||||
|
$router->get('/articulos/{id}', new ArticuloController($gateway));
|
||||||
|
|
||||||
|
$response = $router->dispatch(new JsonRequest(method: 'GET', path: '/articulos/1'));
|
||||||
|
|
||||||
|
self::assertSame(200, $response->status());
|
||||||
|
self::assertSame('Taladro', $response->body()['nombre']);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Test de seguridad
|
||||||
|
|
||||||
|
```php
|
||||||
|
public function testRejectsWithoutToken(): void
|
||||||
|
{
|
||||||
|
$router = (new Router())->withMiddleware(
|
||||||
|
new BearerAuth(static fn (string $t): ?array => null),
|
||||||
|
);
|
||||||
|
$router->get('/privado', static fn (): Response => new Response(['secret' => true]));
|
||||||
|
|
||||||
|
$response = $router->dispatch(new JsonRequest(path: '/privado'));
|
||||||
|
|
||||||
|
self::assertSame(401, $response->status());
|
||||||
|
self::assertStringNotContainsString('secret', $response->toJson());
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Middleware que no toca el reloj
|
||||||
|
|
||||||
|
`RateLimit` acepta `clock` para no esperar 60 segundos en un test:
|
||||||
|
|
||||||
|
```php
|
||||||
|
$now = 1000;
|
||||||
|
$limiter = new RateLimit(limit: 1, windowSeconds: 60, clock: fn (): int => $now);
|
||||||
|
|
||||||
|
$limiter->process($request, $handler); // 200
|
||||||
|
$limiter->process($request, $handler); // 429
|
||||||
|
|
||||||
|
$now += 61;
|
||||||
|
$limiter->process($request, $handler); // 200
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 12. Recetas frecuentes
|
||||||
|
|
||||||
|
### Ruta protegida solo para un endpoint
|
||||||
|
|
||||||
|
```php
|
||||||
|
$router = new Router();
|
||||||
|
$router->get('/publico', $publico);
|
||||||
|
$router->get('/privado', $privado);
|
||||||
|
|
||||||
|
$router = $router->withMiddleware(new BearerAuth($verify));
|
||||||
|
```
|
||||||
|
|
||||||
|
Un router con middleware aplica a **todas** sus rutas. Para mezclar, usá dos routers o un handler
|
||||||
|
que decida.
|
||||||
|
|
||||||
|
### Respuesta sin cuerpo
|
||||||
|
|
||||||
|
```php
|
||||||
|
return $this->noContent(); // 204, body null, toJson() === ''
|
||||||
|
```
|
||||||
|
|
||||||
|
### Validación antes de escribir
|
||||||
|
|
||||||
|
```php
|
||||||
|
public function store(Request $request): Response
|
||||||
|
{
|
||||||
|
$body = $request->body();
|
||||||
|
$errors = [];
|
||||||
|
|
||||||
|
if (trim((string) ($body['nombre'] ?? '')) === '') {
|
||||||
|
$errors['nombre'][] = 'Required.';
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($errors !== []) {
|
||||||
|
return $this->error(new ValidationFailed($errors));
|
||||||
|
}
|
||||||
|
|
||||||
|
return parent::store($request);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Capturar un duplicado del ORM
|
||||||
|
|
||||||
|
```php
|
||||||
|
use Camelia\Orm\Exception\DuplicateKeyException;
|
||||||
|
|
||||||
|
public function store(Request $request): Response
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
return parent::store($request);
|
||||||
|
} catch (DuplicateKeyException) {
|
||||||
|
return $this->error(new Conflict('That record already exists.'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Endpoint que no es CRUD
|
||||||
|
|
||||||
|
```php
|
||||||
|
$router->post('/login', static function (Request $request): Response {
|
||||||
|
$body = $request->body();
|
||||||
|
|
||||||
|
if (!isset($body['email'], $body['password'])) {
|
||||||
|
return new Response(['error' => ['code' => 'bad_request', 'message' => 'Missing credentials.']], 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
$token = Auth::attempt($body['email'], $body['password']);
|
||||||
|
|
||||||
|
return $token === null
|
||||||
|
? new Response(['error' => ['code' => 'unauthorized', 'message' => 'Invalid credentials.']], 401)
|
||||||
|
: new Response(['token' => $token]);
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 13. Trampas y errores comunes
|
||||||
|
|
||||||
|
### `catch (HttpError)` necesita su `use`
|
||||||
|
|
||||||
|
Si escribís un middleware propio con `catch (HttpError $e)`, importá
|
||||||
|
`Camelia\Controllers\Exception\HttpError`. Sin el import, PHP lo resuelve a
|
||||||
|
`Camelia\Controllers\HttpError` (inexistente), el catch nunca coincide y **un 404 sale como 500**.
|
||||||
|
|
||||||
|
### `render()` a mano no ve el `{id}`
|
||||||
|
|
||||||
|
`CrudController` lee `$request->attribute('id')`. Solo el `Router` lo puebla. Llamar
|
||||||
|
`$controller->render($request)` en un test sin `->withAttribute('id', '7')` devuelve **400**, no 200.
|
||||||
|
|
||||||
|
```php
|
||||||
|
// Mal
|
||||||
|
$controller->render(new JsonRequest(method: 'GET', path: '/articulos/7'));
|
||||||
|
|
||||||
|
// Bien
|
||||||
|
$router->dispatch(new JsonRequest(method: 'GET', path: '/articulos/7'));
|
||||||
|
```
|
||||||
|
|
||||||
|
### El orden del pipeline importa
|
||||||
|
|
||||||
|
`Cors` antes de `BearerAuth`. Si no, el preflight `OPTIONS` devuelve 401 y el navegador nunca envía
|
||||||
|
la petición real.
|
||||||
|
|
||||||
|
### `RateLimit` es por proceso
|
||||||
|
|
||||||
|
Detrás de 4 workers PHP-FPM, `limit: 60` significa 240 por minuto en la práctica. Si necesitás un
|
||||||
|
límite real, compartí estado (Redis/APCu) en tu propia implementación de `Middleware`.
|
||||||
|
|
||||||
|
### `ContentNegotiation` no comprime
|
||||||
|
|
||||||
|
No le pidas gzip. Configurá `gzip` en nginx/Apache.
|
||||||
|
|
||||||
|
### `json_encode` puede lanzar
|
||||||
|
|
||||||
|
`Response::toJson()` usa `JSON_THROW_ON_ERROR`. Un cuerpo con recursos, `NAN` o UTF-8 inválido lanza
|
||||||
|
`JsonException` en el `echo` del `index.php`, fuera del try del router. Sanitizá lo que devolvés.
|
||||||
|
|
||||||
|
### Los status son contrato
|
||||||
|
|
||||||
|
Cambiar el 401 de `RequireRole` a 403, o el `code` de un error, rompe a los clientes que ramifican
|
||||||
|
por esos valores.
|
||||||
|
|
||||||
|
### `find*` nunca escribe
|
||||||
|
|
||||||
|
Si un método se llama `findAlgo`, no debe mutar nada. Es la regla de nomenclatura del ecosistema.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 14. Referencia de API
|
||||||
|
|
||||||
|
### `Controller` (abstracta)
|
||||||
|
|
||||||
|
| Método | Devuelve |
|
||||||
|
|---|---|
|
||||||
|
| `render(Request): Response` | **abstracto**, obligatorio |
|
||||||
|
| `json(mixed, int = 200, array = []): Response` | `protected` |
|
||||||
|
| `page(array, int, int, int): Response` | `protected` |
|
||||||
|
| `created(mixed, string): Response` | `protected`, 201 + `Location` |
|
||||||
|
| `noContent(): Response` | `protected`, 204 |
|
||||||
|
| `error(HttpError): Response` | `protected` |
|
||||||
|
| `notFound(string): Response` | `protected` |
|
||||||
|
|
||||||
|
### `CrudController`
|
||||||
|
|
||||||
|
| Miembro | |
|
||||||
|
|---|---|
|
||||||
|
| `__construct(ResourceGateway, string $resource)` | |
|
||||||
|
| `render(Request): Response` | despacha por método + `id` |
|
||||||
|
| `index/show/store/update/destroy(Request): Response` | públicas, sobrescribibles |
|
||||||
|
| `resourceName(): string` | |
|
||||||
|
| `allowedMethods(bool $hasId): list<string>` | |
|
||||||
|
|
||||||
|
### `Router`
|
||||||
|
|
||||||
|
| Método | |
|
||||||
|
|---|---|
|
||||||
|
| `get/post/put/patch/delete(pattern, handler)` | encadenables |
|
||||||
|
| `add(string $method, string $pattern, mixed $handler)` | |
|
||||||
|
| `withMiddleware(Middleware): self` | devuelve copia |
|
||||||
|
| `pipeline(): Pipeline` | |
|
||||||
|
| `routes(): list<Route>` | |
|
||||||
|
| `dispatch(Request): Response` | nunca lanza |
|
||||||
|
|
||||||
|
### `Route`
|
||||||
|
|
||||||
|
`method()`, `pattern()`, `handler()`, `parameters(): list<string>`,
|
||||||
|
`matches(string $path): ?array`.
|
||||||
|
|
||||||
|
### `Response`
|
||||||
|
|
||||||
|
`body()`, `status()`, `headers()`, `isSuccessful()`, `hasHeader(string)`,
|
||||||
|
`withHeader(string, string)`, `toJson(int $flags = 0)`, `Response::noContent()`.
|
||||||
|
|
||||||
|
### `JsonRequest`
|
||||||
|
|
||||||
|
`method()`, `path()`, `query(string, mixed = null)`, `body()`, `header(string)`,
|
||||||
|
`attribute(string)`, `withAttribute(string, mixed)`.
|
||||||
|
|
||||||
|
### `Pipeline`
|
||||||
|
|
||||||
|
`__construct(list<Middleware>)`, `with(Middleware): self`, `middlewares()`, `isEmpty()`,
|
||||||
|
`process(Request, callable): Response`.
|
||||||
|
|
||||||
|
### Middlewares
|
||||||
|
|
||||||
|
| Clase | Constructor |
|
||||||
|
|---|---|
|
||||||
|
| `Security\BearerAuth` | `(callable $resolver)` |
|
||||||
|
| `Security\RequireRole` | `(list<string> $roles)` |
|
||||||
|
| `Security\RateLimit` | `(int $limit = 60, int $windowSeconds = 60, ?callable $clock, ?callable $keyResolver)` |
|
||||||
|
| `Security\Cors` | `(list $allowedOrigins = ['*'], list $allowedMethods, list $allowedHeaders, bool $allowCredentials = false, int $maxAge = 86400)` |
|
||||||
|
| `Middleware\Logging` | `(callable $sink, ?callable $clock = null)` |
|
||||||
|
| `Middleware\ContentNegotiation` | `(list $acceptedTypes = ['application/json', '*/*'], bool $addContentType = true)` |
|
||||||
|
|
||||||
|
### Excepciones
|
||||||
|
|
||||||
|
`BadRequest` (400) · `Unauthorized` (401) · `NotFound` (404) · `MethodNotAllowed` (405) ·
|
||||||
|
`Conflict` (409) · `ValidationFailed` (422) · `ServerError` (500), todas bajo
|
||||||
|
`Camelia\Controllers\Exception`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Por dónde seguir
|
||||||
|
|
||||||
|
- **[EJEMPLOS.md](EJEMPLOS.md)** — una API de facturación completa, ensamblada de punta a punta.
|
||||||
|
- **[ARQUITECTURA.md](ARQUITECTURA.md)** — por qué cada decisión es como es.
|
||||||
|
- **[especificaciones-controllers.md](especificaciones-controllers.md)** — el contrato normativo.
|
||||||
+101
@@ -0,0 +1,101 @@
|
|||||||
|
# Documentación de `camelia/controllers`
|
||||||
|
|
||||||
|
Toolkit para construir APIs REST rápido, en PHP vanilla y sin framework.
|
||||||
|
|
||||||
|
## Índice
|
||||||
|
|
||||||
|
| Documento | Para qué sirve |
|
||||||
|
|---|---|
|
||||||
|
| [GUIA-PROGRAMADOR.md](GUIA-PROGRAMADOR.md) | Guía paso a paso: instalación, primer endpoint, CRUD, seguridad y testing. **Empieza aquí.** |
|
||||||
|
| [EJEMPLOS.md](EJEMPLOS.md) | Una API de facturación completa, con adaptador de ORM, router, seguridad y tests. |
|
||||||
|
| [ARQUITECTURA.md](ARQUITECTURA.md) | Por qué está diseñado así y qué se descartó a propósito. |
|
||||||
|
| [especificaciones-controllers.md](especificaciones-controllers.md) | Documento normativo. Define el contrato: nombres, formas JSON, códigos. |
|
||||||
|
|
||||||
|
## Qué es
|
||||||
|
|
||||||
|
Una librería que resuelve la capa HTTP de una API REST:
|
||||||
|
|
||||||
|
- **Routing** con parámetros (`/articulos/{id}`), 404 y 405 con `Allow`.
|
||||||
|
- **Request/Response** inmutables. Nada se imprime: se devuelve un objeto.
|
||||||
|
- **CRUD genérico** sobre un puerto `ResourceGateway` que la app implementa.
|
||||||
|
- **Middlewares** componibles: autenticación, roles, rate limit, CORS, logging, negociación.
|
||||||
|
|
||||||
|
## Qué NO es
|
||||||
|
|
||||||
|
- No es un framework. No trae contenedor de dependencias, ni ORM, ni plantillas.
|
||||||
|
- No lee superglobales. Todo entra por `Request`.
|
||||||
|
- No emite la respuesta. Eso lo hace tu `index.php` en cinco líneas.
|
||||||
|
- No comprime, no sirve archivos estáticos, no gestiona sesiones.
|
||||||
|
|
||||||
|
## Inicio en 30 segundos
|
||||||
|
|
||||||
|
```bash
|
||||||
|
composer require camelia/controllers
|
||||||
|
```
|
||||||
|
|
||||||
|
```php
|
||||||
|
<?php
|
||||||
|
// index.php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
require __DIR__ . '/vendor/autoload.php';
|
||||||
|
|
||||||
|
use Camelia\Controllers\{JsonRequest, Router, Response, Security\Cors};
|
||||||
|
|
||||||
|
$router = (new Router())->withMiddleware(new Cors());
|
||||||
|
|
||||||
|
$router->get('/salud', static fn (): Response => new Response(['status' => 'ok']));
|
||||||
|
|
||||||
|
$request = new JsonRequest(
|
||||||
|
method: $_SERVER['REQUEST_METHOD'] ?? 'GET',
|
||||||
|
path: parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/',
|
||||||
|
query: $_GET,
|
||||||
|
headers: ['origin' => $_SERVER['HTTP_ORIGIN'] ?? ''],
|
||||||
|
);
|
||||||
|
|
||||||
|
$response = $router->dispatch($request);
|
||||||
|
|
||||||
|
http_response_code($response->status());
|
||||||
|
|
||||||
|
foreach ($response->headers() as $name => $value) {
|
||||||
|
header($name . ': ' . $value);
|
||||||
|
}
|
||||||
|
|
||||||
|
echo $response->toJson();
|
||||||
|
```
|
||||||
|
|
||||||
|
Un `GET /salud` devuelve `{"status":"ok"}` con status 200.
|
||||||
|
|
||||||
|
## Requisitos
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| PHP | `>=8.3` |
|
||||||
|
| Extensiones | `ext-json` |
|
||||||
|
| Dependencias de runtime | **ninguna** |
|
||||||
|
| Testing | PHPUnit `^10.5 \|\| ^11.0` |
|
||||||
|
|
||||||
|
## Estructura del código
|
||||||
|
|
||||||
|
```
|
||||||
|
src/
|
||||||
|
├── Controller.php base con helpers de respuesta
|
||||||
|
├── CrudController.php CRUD REST sobre ResourceGateway
|
||||||
|
├── Router.php registro y despacho de rutas
|
||||||
|
├── Route.php ruta compilada
|
||||||
|
├── Pipeline.php cadena de middlewares
|
||||||
|
├── Middleware.php interfaz (forma PSR-15)
|
||||||
|
├── Request.php interfaz de entrada
|
||||||
|
├── JsonRequest.php implementación desde arrays
|
||||||
|
├── Response.php respuesta inmutable
|
||||||
|
├── ResourceGateway.php puerto de datos
|
||||||
|
├── Security/ BearerAuth, RequireRole, RateLimit, Cors
|
||||||
|
├── Middleware/ Logging, ContentNegotiation
|
||||||
|
└── Exception/ HttpError y sus 7 concreciones
|
||||||
|
```
|
||||||
|
|
||||||
|
## Convenciones que conviene saber
|
||||||
|
|
||||||
|
- **Claves JSON en `snake_case`** (`per_page`, `total_pages`); código PHP en `camelCase`.
|
||||||
|
- **Todo error lanza**; nada degrada a una respuesta vacía.
|
||||||
|
- **Los status y las formas JSON son contrato público.** Cambiarlos es cambio de API.
|
||||||
@@ -0,0 +1,398 @@
|
|||||||
|
# Especificaciones de `camelia-controllers` — toolkit REST sin framework
|
||||||
|
|
||||||
|
Documento normativo y **autosuficiente** para construir una librería PHP 8.3+ de controllers REST.
|
||||||
|
No asume ningún otro documento.
|
||||||
|
|
||||||
|
> Define el contrato. Cuando una decisión tenga más de una salida razonable, se explica la elegida.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0. Nomenclatura canónica
|
||||||
|
|
||||||
|
**Este glosario es normativo.** Todo nombre de clase, método y parámetro proviene de esta tabla.
|
||||||
|
|
||||||
|
Regla de formación: **el nombre dice qué es, no de dónde viene.**
|
||||||
|
|
||||||
|
- **Clases**: sustantivo singular en `PascalCase`. `Response`, no `ApiOutput`.
|
||||||
|
- **Interfaces**: capacidad, sin prefijo `I` ni sufijo `Interface`. `ResourceGateway`, `Request`.
|
||||||
|
- **Métodos de lectura**: prefijo `find`. **Escrituras**: verbo de destino. Un `find*` nunca escribe.
|
||||||
|
- **Booleanos**: `is`/`has`/`can`. `isSuccessful()`, `hasHeader()`.
|
||||||
|
- **Colecciones**: plural. `items`, `headers`.
|
||||||
|
- **Sin abreviaturas**: `Request`, no `Req`; `Response`, no `Resp`; `Controller`, no `Ctrl`.
|
||||||
|
- **La implementación lleva el prefijo del origen**: `JsonRequest`; la interfaz, el rol: `Request`.
|
||||||
|
- **Claves JSON en `snake_case`**; código PHP en `camelCase`. Igual que `Page::toArray()` del ORM.
|
||||||
|
|
||||||
|
### 0.1 Nombres prohibidos
|
||||||
|
|
||||||
|
`BaseController` · `AbstractController` · `ApiCtrl` · `RouterService` · `HttpHelper` · `ResponseDto` ·
|
||||||
|
`RequestInterface` (el sufijo ya está prohibido) · `ControllerTrait`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Resumen ejecutivo
|
||||||
|
|
||||||
|
`camelia-controllers` construye APIs REST rápido: routing con parámetros, parsing de request,
|
||||||
|
respuestas JSON y un CRUD completo sobre un puerto de datos. **PHP vanilla, sin framework.**
|
||||||
|
|
||||||
|
- **Paquete:** `camelia/controllers` · **namespace raíz:** `Camelia\Controllers`
|
||||||
|
- **PHP:** `>=8.3` · **ext-json** (obligatoria)
|
||||||
|
- **Dependencias de runtime:** **ninguna**. Ni `camelia/orm` (§3).
|
||||||
|
- **PSR-4:** `Camelia\Controllers\` → `src/`
|
||||||
|
|
||||||
|
### Principios rectores
|
||||||
|
|
||||||
|
| Principio | Cómo se materializa |
|
||||||
|
|---|---|
|
||||||
|
| **Nada se imprime** | Ninguna clase hace `echo`, `header()`, `die` ni `exit`. Siempre se devuelve `Response`. |
|
||||||
|
| **Sin superglobales** | El request entra solo por `Request`. `$_GET`/`$_POST`/`$_SERVER` no aparecen en `src/`. |
|
||||||
|
| **Independiente** | Los datos llegan por `ResourceGateway`. La app conecta el ORM con un adaptador. |
|
||||||
|
| **Todo error es tipado** | Toda falla se traduce a `HttpError` con su status. No hay degradación silenciosa. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Anatomía
|
||||||
|
|
||||||
|
```
|
||||||
|
src/
|
||||||
|
├── Controller.php S1-S3 base: helpers de respuesta
|
||||||
|
├── CrudController.php S6-S9 CRUD sobre ResourceGateway
|
||||||
|
├── Router.php S10-S12 registro y despacho
|
||||||
|
├── Pipeline.php S14 cadena de middlewares
|
||||||
|
├── Middleware.php S14 interfaz PSR-15-shaped
|
||||||
|
├── Request.php S4 interfaz de entrada
|
||||||
|
├── JsonRequest.php S5 implementación desde arrays
|
||||||
|
├── Response.php S2 respuesta inmutable
|
||||||
|
├── Route.php S10 ruta compilada
|
||||||
|
├── ResourceGateway.php S6 puerto de datos
|
||||||
|
├── Security/
|
||||||
|
│ ├── BearerAuth.php S15 autenticación Bearer
|
||||||
|
│ ├── RequireRole.php S16 autorización por rol
|
||||||
|
│ ├── RateLimit.php S17 límite por ventana fija
|
||||||
|
│ └── Cors.php S18 cabeceras CORS + preflight
|
||||||
|
├── Middleware/
|
||||||
|
│ ├── Logging.php S19 una línea por request
|
||||||
|
│ └── ContentNegotiation.php S20 acepta JSON / 406 / Content-Type
|
||||||
|
└── Exception/
|
||||||
|
├── ControllerException.php S13 raíz
|
||||||
|
├── HttpError.php S13 error con status + forma JSON
|
||||||
|
├── NotFound.php S13 404
|
||||||
|
├── BadRequest.php S13 400
|
||||||
|
├── MethodNotAllowed.php S13 405
|
||||||
|
├── ValidationFailed.php S13 422
|
||||||
|
├── Conflict.php S13 409
|
||||||
|
├── Unauthorized.php S13 401
|
||||||
|
└── ServerError.php S13 500
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Independencia del ORM
|
||||||
|
|
||||||
|
`composer.json` **no** requiere `camelia/orm`. Todo acceso a datos pasa por `ResourceGateway`, que la
|
||||||
|
aplicación implementa (típicamente con `Camelia\Orm\Repository`). En `src/` está prohibido importar
|
||||||
|
`Camelia\Orm\*`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. `Request` (interfaz)
|
||||||
|
|
||||||
|
```php
|
||||||
|
interface Request
|
||||||
|
{
|
||||||
|
public function method(): string; // 'GET', 'POST'… en mayúsculas
|
||||||
|
public function path(): string; // '/articulos/7', sin query string
|
||||||
|
public function query(string $key, mixed $default = null): mixed;
|
||||||
|
public function body(): array; // cuerpo ya decodificado
|
||||||
|
public function header(string $name): ?string;
|
||||||
|
public function attribute(string $key): mixed; // parámetros de ruta ya poblados
|
||||||
|
public function withAttribute(string $key, mixed $value): static; // copia inmutable
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. `JsonRequest`
|
||||||
|
|
||||||
|
Implementación inmutable sobre arrays. Es lo que se usa en tests y lo que un adaptador construye
|
||||||
|
desde PSR-7 o superglobales.
|
||||||
|
|
||||||
|
```php
|
||||||
|
new JsonRequest(
|
||||||
|
method: 'GET',
|
||||||
|
path: '/articulos/7',
|
||||||
|
query: ['page' => '2'],
|
||||||
|
body: ['nombre' => 'Taladro'],
|
||||||
|
headers: ['accept' => 'application/json'],
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
- `query()` y `body()` solo leen del array inyectado; nunca de superglobales.
|
||||||
|
- `withAttribute()` devuelve **copia** nueva (inmutable).
|
||||||
|
- `header()` normaliza el nombre a minúsculas: `Accept` y `accept` son la misma cabecera.
|
||||||
|
- Un `body` no-array o un JSON inválido se rechaza en el adaptador, no aquí.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. `ResourceGateway` (puerto de datos)
|
||||||
|
|
||||||
|
```php
|
||||||
|
interface ResourceGateway
|
||||||
|
{
|
||||||
|
/** @return list<array<string, mixed>> */
|
||||||
|
public function findAll(array $query = []): array;
|
||||||
|
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
public function find(int|string $id): ?array;
|
||||||
|
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
public function create(array $values): array;
|
||||||
|
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
public function update(int|string $id, array $values): ?array;
|
||||||
|
|
||||||
|
/** @return bool true si borró algo */
|
||||||
|
public function delete(int|string $id): bool;
|
||||||
|
|
||||||
|
/** @return int|null conteo total; null si el gateway no sabe contar */
|
||||||
|
public function count(array $query = []): ?int;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- Los registros se representan como arrays asociativos; serializarlos es del controller.
|
||||||
|
- `find`/`update` devuelven `null` cuando el registro no existe. El `CrudController` lo convierte en
|
||||||
|
404; el gateway **no** lanza excepciones HTTP.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. `Controller`
|
||||||
|
|
||||||
|
Clase abstracta base. **No** implementa acciones: aporta helpers de respuesta y el acceso a request.
|
||||||
|
|
||||||
|
```php
|
||||||
|
abstract class Controller
|
||||||
|
{
|
||||||
|
protected function json(mixed $data, int $status = 200, array $headers = []): Response;
|
||||||
|
protected function noContent(): Response; // 204, sin cuerpo
|
||||||
|
protected function created(mixed $data, string $location): Response; // 201 + Location
|
||||||
|
protected function error(HttpError $error): Response; // status + forma JSON
|
||||||
|
protected function page(array $items, int $page, int $perPage, int $total): Response;
|
||||||
|
protected function render(Request $request): Response; // plantilla abstracta
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`render()` es el único método abstracto: cada controller concreto decide su despacho.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. `CrudController extends Controller`
|
||||||
|
|
||||||
|
Implementa las cinco acciones REST estándar sobre un `ResourceGateway`.
|
||||||
|
|
||||||
|
| Acción | Método | Ruta | Status |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `index` | GET | `/recurso` | 200 + página |
|
||||||
|
| `show` | GET | `/recurso/{id}` | 200 / 404 |
|
||||||
|
| `store` | POST | `/recurso` | 201 + `Location` |
|
||||||
|
| `update` | PUT/PATCH | `/recurso/{id}` | 200 / 404 |
|
||||||
|
| `destroy` | DELETE | `/recurso/{id}` | 204 / 404 |
|
||||||
|
|
||||||
|
Paginación: lee `page` y `per_page` del query string. `page` mínimo 1; `per_page` se recorta al rango
|
||||||
|
`1..1000` (mismo rango que el ORM). Forma de la página:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "items": [], "page": 1, "per_page": 20, "total": 0, "total_pages": 0,
|
||||||
|
"has_next": false, "has_prev": false }
|
||||||
|
```
|
||||||
|
|
||||||
|
El nombre del recurso para `Location` se resuelve con `resourceName()`, que cada subclase define.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Especialización por recurso
|
||||||
|
|
||||||
|
```php
|
||||||
|
final class ArticuloController extends CrudController
|
||||||
|
{
|
||||||
|
public function __construct(ArticuloGateway $gateway)
|
||||||
|
{
|
||||||
|
parent::__construct($gateway, 'articulos');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`render()` en `CrudController` despacha según `method` + `attribute('id')`, así el `Router` solo
|
||||||
|
necesita llamar `render($request)`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. `Route` y `Router`
|
||||||
|
|
||||||
|
```php
|
||||||
|
$router = new Router();
|
||||||
|
$router->get('/articulos', $controller); // handler: objeto Controller
|
||||||
|
$router->post('/articulos', $controller);
|
||||||
|
$router->get('/articulos/{id}', $controller);
|
||||||
|
|
||||||
|
$response = $router->dispatch($request); // Response
|
||||||
|
```
|
||||||
|
|
||||||
|
- Patrón con parámetros `{id}`; se capturan como atributos del request (`attribute('id')`).
|
||||||
|
- Ruta no encontrada → 404. Ruta encontrada con otro método → **405** con cabecera `Allow`.
|
||||||
|
- Un handler puede ser `Controller` (se llama `render`) o `callable(Request): Response`.
|
||||||
|
- `Route::matches(string $path): ?array` devuelve los parámetros capturados o `null`.
|
||||||
|
- Los parámetros se comparan como string; `{id}` acepta `42` y `abc`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11. `Response`
|
||||||
|
|
||||||
|
Inmutable y `final readonly`.
|
||||||
|
|
||||||
|
```php
|
||||||
|
new Response(mixed $body, int $status = 200, array $headers = []);
|
||||||
|
```
|
||||||
|
|
||||||
|
- `body` es `mixed`; si es array/objeto se serializa a JSON al emitir.
|
||||||
|
- `status()`, `headers()`, `body()`, `isSuccessful()` (2xx), `withHeader(string, string): self`.
|
||||||
|
- `toJson(int $flags = 0): string` — `JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES`.
|
||||||
|
- No emite nada: una función externa hace `http_response_code()` y escribe el cuerpo.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 12. `HttpError` y la jerarquía
|
||||||
|
|
||||||
|
```php
|
||||||
|
abstract class HttpError extends ControllerException
|
||||||
|
{
|
||||||
|
abstract public function status(): int;
|
||||||
|
abstract public function errorCode(): string; // 'not_found', 'validation_failed'…
|
||||||
|
public function headers(): array; // por defecto []
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Forma JSON de todo error:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "error": { "code": "not_found", "message": "Articulo 7 does not exist." } }
|
||||||
|
```
|
||||||
|
|
||||||
|
| Clase | Status | `errorCode()` | Extra |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `BadRequest` | 400 | `bad_request` | — |
|
||||||
|
| `Unauthorized` | 401 | `unauthorized` | — |
|
||||||
|
| `NotFound` | 404 | `not_found` | — |
|
||||||
|
| `MethodNotAllowed` | 405 | `method_not_allowed` | `headers()` → `['Allow' => 'GET, POST']` |
|
||||||
|
| `Conflict` | 409 | `conflict` | — |
|
||||||
|
| `ValidationFailed` | 422 | `validation_failed` | incluye `"errors": {campo: [mensajes]}` |
|
||||||
|
| `ServerError` | 500 | `server_error` | el mensaje se sustituye por uno genérico si se construye desde un `Throwable` |
|
||||||
|
|
||||||
|
`ValidationFailed` añade `errors()` con la forma `array<string, list<string>>` que ya usa
|
||||||
|
`Camelia\Orm\Exception\ValidationException`, para que el adaptador la mapee sin traducción.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 13. Reglas de comportamiento
|
||||||
|
|
||||||
|
1. `Controller::error()` nunca propaga: convierte cualquier `HttpError` en `Response`.
|
||||||
|
2. Un `Throwable` que no es `HttpError` sale como `ServerError` con mensaje genérico (no filtra
|
||||||
|
detalles internos al cliente).
|
||||||
|
3. Todos los códigos y formas JSON de §12 son **contrato público**: cambiarlos es cambio de API.
|
||||||
|
4. Sin estado estático mutable. Dos requests nunca comparten datos.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 14. `Middleware` y `Pipeline`
|
||||||
|
|
||||||
|
```php
|
||||||
|
interface Middleware
|
||||||
|
{
|
||||||
|
/** @param callable(Request): Response $next */
|
||||||
|
public function process(Request $request, callable $next): Response;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- Delega llamando `$next($request)`, o corta devolviendo un `Response` sin llamarlo.
|
||||||
|
- Forma PSR-15 sin depender de `psr/http-*`: la librería sigue sin dependencias de runtime.
|
||||||
|
- `Pipeline` es **inmutable**. `with()` devuelve copia; `process()` ejecuta de fuera hacia dentro
|
||||||
|
(el primero añadido es el más externo). Un middleware posterior envuelve al anterior.
|
||||||
|
|
||||||
|
```php
|
||||||
|
$router = (new Router())
|
||||||
|
->withMiddleware(new Cors())
|
||||||
|
->withMiddleware(new RateLimit(limit: 100))
|
||||||
|
->withMiddleware(new BearerAuth($verify))
|
||||||
|
->withMiddleware(new RequireRole(['admin']));
|
||||||
|
```
|
||||||
|
|
||||||
|
`Router::withMiddleware()` devuelve copia del router; el original queda intacto. El orden importa:
|
||||||
|
`Cors` primero (responde el preflight sin autenticar), `BearerAuth` antes de `RequireRole`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 15. `Security\BearerAuth`
|
||||||
|
|
||||||
|
- Lee `Authorization: Bearer <token>` (esquema insensible a mayúsculas).
|
||||||
|
- Sin cabecera, esquema distinto, o token inválido → **401** + `WWW-Authenticate: Bearer`.
|
||||||
|
- Con token válido adjunta la identidad en el atributo `user`.
|
||||||
|
- Valida con un `callable(string $token): array|null` inyectado. La librería **no** implementa JWT
|
||||||
|
ni criptografía: si devuelve `null`, el token se rechaza.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 16. `Security\RequireRole`
|
||||||
|
|
||||||
|
- Lee la identidad del atributo `user` que dejó `BearerAuth`.
|
||||||
|
- Roles en `$identity['roles']` (lista) o `$identity['role']` (string único); cualquier rol de la
|
||||||
|
lista configurada concede acceso.
|
||||||
|
- **Falla cerrado**: sin identidad, identidad no-array, o roles malformados → 401. Nunca 200.
|
||||||
|
- Un array de roles vacío en el constructor lanza `BadRequest`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 17. `Security\RateLimit`
|
||||||
|
|
||||||
|
- Ventana fija por clave: cuenta y `resetAt`. Al pasar el límite → **429** con `Retry-After`.
|
||||||
|
- Cabeceras en toda respuesta: `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`
|
||||||
|
(epoch en segundos, así lo entrega el servidor).
|
||||||
|
- Clave por defecto: atributo `client_ip` del request; sin él, un bucket compartido `anonymous`.
|
||||||
|
Hay `keyResolver` y `clock` inyectables para testear sin esperar.
|
||||||
|
- **Estado en proceso.** Detrás de N workers el límite efectivo se multiplica por N. Es una
|
||||||
|
limitación conocida, no un bug: la librería no depende de Redis ni APCu.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 18. `Security\Cors`
|
||||||
|
|
||||||
|
- `OPTIONS` responde **204** sin llegar al handler.
|
||||||
|
- Origen `*` + `allowCredentials: true` es inválido en navegadores: en ese caso se repite el origen
|
||||||
|
exacto y se añade `Access-Control-Allow-Credentials: true`.
|
||||||
|
- Un origen no permitido **no** recibe `Access-Control-Allow-Origin` (la petición falla en el
|
||||||
|
navegador, que es el comportamiento correcto).
|
||||||
|
- Siempre envía `Vary: Origin` para que ningún proxy cachee la cabecera equivocada.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 19. `Middleware\Logging`
|
||||||
|
|
||||||
|
- Una entrada por request: método, ruta, status y `duration_ms`.
|
||||||
|
- Nivel derivado del status: `5xx` → `error`, `4xx` → `warning`, resto → `info`.
|
||||||
|
- El destino es un `callable(string $level, string $message, array $context): void`, **no** un logger
|
||||||
|
PSR-3: el paquete sigue con cero dependencias. Se conecta cualquier PSR-3 con
|
||||||
|
`$logger->log(...)`.
|
||||||
|
- Un `Throwable` del handler se registra como 500 y **se relanza**: el mapeo a `Response` lo hace
|
||||||
|
`Router`, no el logger.
|
||||||
|
- `clock` inyectable en milisegundos; por defecto `hrtime(true)`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 20. `Middleware\ContentNegotiation`
|
||||||
|
|
||||||
|
- Si el `Accept` del cliente no casa con ninguno de los tipos aceptados → **406** con el código
|
||||||
|
`not_acceptable` y una cabecera `Accept` listando lo que sí produce.
|
||||||
|
- Un `Accept` ausente o vacío acepta todo (RFC 9110).
|
||||||
|
- Una entrada con `q=0` **no** cuenta como aceptada.
|
||||||
|
- Añade `Content-Type: application/json; charset=utf-8` si la respuesta no trae ya uno.
|
||||||
|
- **No comprime el cuerpo.** `Response` es inmutable y el adaptador serializa; un `gzencode()` aquí
|
||||||
|
duplicaría el trabajo y rompería `Content-Length`. Eso es del servidor (`gzip`/`mod_deflate`).
|
||||||
|
- Orden sugerido: el **más externo** del pipeline, antes de `Cors`, para que un 406 también lleve
|
||||||
|
las cabeceras CORS y el navegador pueda leerlo.
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
# Mago toolchain configuration — camelia/controllers
|
||||||
|
# Docs: https://mago.carthage.software
|
||||||
|
|
||||||
|
# The library promises PHP >= 8.3. Pinning the parser to 8.2 keeps the formatter from emitting
|
||||||
|
# syntax the package cannot ship (for example `new Foo()->bar()`, which needs 8.4).
|
||||||
|
php-version = "8.2"
|
||||||
|
|
||||||
|
[source]
|
||||||
|
paths = ["src", "tests"]
|
||||||
|
includes = ["vendor"]
|
||||||
|
excludes = ["vendor", ".phpunit.cache", ".mago.cache"]
|
||||||
|
extensions = ["php"]
|
||||||
|
|
||||||
|
[formatter]
|
||||||
|
print-width = 100
|
||||||
|
tab-width = 4
|
||||||
|
use-tabs = false
|
||||||
|
end-of-line = "lf"
|
||||||
|
single-quote = true
|
||||||
|
trailing-comma = true
|
||||||
|
remove-trailing-close-tag = true
|
||||||
|
function-brace-style = "next-line"
|
||||||
|
method-brace-style = "next-line"
|
||||||
|
classlike-brace-style = "always-next-line"
|
||||||
|
|
||||||
|
# Disabled: this option rewrites `(new Foo())->bar()` into `new Foo()->bar()`, which is a PHP parse
|
||||||
|
# error whenever the result is assigned or returned. Reproduced with mago 1.60.1 on every run, so the
|
||||||
|
# key is turned off until the formatter is fixed upstream. Keep the parentheses: valid PHP.
|
||||||
|
first-method-chain-on-new-line = false
|
||||||
|
|
||||||
|
[analyzer]
|
||||||
|
# Tests are excluded from the Mago analyzer: they extend PHPUnit\Framework\TestCase and Mago does
|
||||||
|
# not load Composer's autoloader for external packages, so every test would report a false
|
||||||
|
# "non-existent class". PHPStan covers tests with the Composer autoloader available.
|
||||||
|
excludes = ["tests"]
|
||||||
|
find-unused-expressions = true
|
||||||
|
find-unused-definitions = true
|
||||||
|
find-unused-parameters = true
|
||||||
|
strict-list-index-checks = true
|
||||||
|
strict-array-index-existence = true
|
||||||
|
check-missing-type-hints = true
|
||||||
|
check-closure-missing-type-hints = true
|
||||||
|
check-use-statements = true
|
||||||
|
check-property-initialization = true
|
||||||
|
check-dead-catch = true
|
||||||
|
|
||||||
|
# Disabled: controllers are a thin translation layer whose contract is "every failure becomes a
|
||||||
|
# typed HTTP error". Annotating @throws on every handler would restate that design instead of
|
||||||
|
# documenting it. Consumers rely on the error-mapping table, not on per-method annotations.
|
||||||
|
check-throws = false
|
||||||
|
|
||||||
|
# Disabled: the boolean parameters left in the public API describe request data (whether a field is
|
||||||
|
# nullable, whether a route is the collection root), not a "do X or do Y" switch. Splitting them
|
||||||
|
# would duplicate every call site for no readability gain.
|
||||||
|
[linter.rules.no-boolean-flag-parameter]
|
||||||
|
enabled = false
|
||||||
|
|
||||||
|
# Disabled: this rule would turn every integer, bool and null literal argument into a named
|
||||||
|
# argument. For PHP standard-library calls such as substr($s, 0, 12) the parameter name adds noise
|
||||||
|
# without adding clarity and makes the diff unreadable.
|
||||||
|
[linter.rules.literal-named-argument]
|
||||||
|
enabled = false
|
||||||
|
|
||||||
|
# Disabled: every isset() here checks key existence in a map whose values are never null (route
|
||||||
|
# params, parsed body fields, header maps). isset() is the idiomatic and faster form for that case.
|
||||||
|
[linter.rules.no-isset]
|
||||||
|
enabled = false
|
||||||
|
|
||||||
|
# Disabled: readability proxies without an actionable change in this codebase.
|
||||||
|
[linter.rules.inline-variable-return]
|
||||||
|
enabled = false
|
||||||
|
|
||||||
|
[linter.rules.no-multi-assignments]
|
||||||
|
enabled = false
|
||||||
|
|
||||||
|
# Metric thresholds are raised on purpose, mirroring ../orm.
|
||||||
|
#
|
||||||
|
# Router, CrudController and the CrudController test mirror the public API contract: one method per
|
||||||
|
# route operation and one test per rule. Splitting them would duplicate the routing and metadata
|
||||||
|
# plumbing this design deliberately keeps in one place. The same reasoning applies to the request
|
||||||
|
# value objects, whose constructor parameters are the request parts (method, path, query, body,
|
||||||
|
# headers, attributes) rather than a control-flow switch.
|
||||||
|
[linter.rules.too-many-methods]
|
||||||
|
threshold = 20
|
||||||
|
|
||||||
|
[linter.rules.excessive-parameter-list]
|
||||||
|
threshold = 8
|
||||||
|
|
||||||
|
[linter.rules.cyclomatic-complexity]
|
||||||
|
threshold = 90
|
||||||
|
method-threshold = 20
|
||||||
|
|
||||||
|
# Disabled: every flagged parameter is the `$token` argument of a test closure built to exercise
|
||||||
|
# BearerAuth. The library marks its own sensitive parameters where they matter; repeating the
|
||||||
|
# attribute across test doubles adds noise without changing runtime behaviour.
|
||||||
|
[linter.rules.sensitive-parameter]
|
||||||
|
enabled = false
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
parameters:
|
||||||
|
level: 8
|
||||||
|
# The library promises PHP >= 8.3, so analysis targets the oldest supported version.
|
||||||
|
# This is why `(new Foo())->bar()` keeps its parentheses: `new Foo()->bar()` only parses on 8.4+.
|
||||||
|
phpVersion: 80300
|
||||||
|
paths:
|
||||||
|
- src
|
||||||
|
- tests
|
||||||
|
treatPhpDocTypesAsCertain: false
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
|
||||||
|
bootstrap="vendor/autoload.php"
|
||||||
|
colors="true"
|
||||||
|
cacheDirectory=".phpunit.cache"
|
||||||
|
failOnWarning="true"
|
||||||
|
failOnRisky="true"
|
||||||
|
failOnEmptyTestSuite="true">
|
||||||
|
<testsuites>
|
||||||
|
<testsuite name="unit">
|
||||||
|
<directory>tests/Unit</directory>
|
||||||
|
</testsuite>
|
||||||
|
</testsuites>
|
||||||
|
<source>
|
||||||
|
<include>
|
||||||
|
<directory>src</directory>
|
||||||
|
</include>
|
||||||
|
</source>
|
||||||
|
</phpunit>
|
||||||
@@ -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());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Camelia\Controllers\Tests\Fixture;
|
||||||
|
|
||||||
|
use Camelia\Controllers\ResourceGateway;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* In-memory gateway: the library's contract is testable without a database.
|
||||||
|
*/
|
||||||
|
final class ArrayGateway implements ResourceGateway
|
||||||
|
{
|
||||||
|
/** @param array<int|string, array<string, mixed>> $records */
|
||||||
|
public function __construct(
|
||||||
|
private array $records = [],
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/** @return list<array<string, mixed>> */
|
||||||
|
public function findAll(array $query = []): array
|
||||||
|
{
|
||||||
|
return array_values($this->records);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string, mixed>|null */
|
||||||
|
public function find(int|string $id): ?array
|
||||||
|
{
|
||||||
|
return $this->records[$id] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
public function create(array $values): array
|
||||||
|
{
|
||||||
|
$id = count($this->records) + 1;
|
||||||
|
$record = ['id' => $id] + $values;
|
||||||
|
$this->records[$id] = $record;
|
||||||
|
|
||||||
|
return $record;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string, mixed>|null */
|
||||||
|
public function update(int|string $id, array $values): ?array
|
||||||
|
{
|
||||||
|
if (!isset($this->records[$id])) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->records[$id] = ['id' => $id] + $values;
|
||||||
|
|
||||||
|
return $this->records[$id];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function delete(int|string $id): bool
|
||||||
|
{
|
||||||
|
if (!isset($this->records[$id])) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
unset($this->records[$id]);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function count(array $query = []): ?int
|
||||||
|
{
|
||||||
|
return count($this->records);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Camelia\Controllers\Tests\Unit;
|
||||||
|
|
||||||
|
use Camelia\Controllers\CrudController;
|
||||||
|
use Camelia\Controllers\JsonRequest;
|
||||||
|
use Camelia\Controllers\Request;
|
||||||
|
use Camelia\Controllers\Response;
|
||||||
|
use Camelia\Controllers\Router;
|
||||||
|
use Camelia\Controllers\Tests\Fixture\ArrayGateway;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
final class CrudControllerTest extends TestCase
|
||||||
|
{
|
||||||
|
private ArrayGateway $gateway;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
$this->gateway = new ArrayGateway([
|
||||||
|
1 => ['id' => 1, 'nombre' => 'Taladro'],
|
||||||
|
2 => ['id' => 2, 'nombre' => 'Sierra'],
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function controller(): CrudController
|
||||||
|
{
|
||||||
|
return new class($this->gateway) extends CrudController {
|
||||||
|
public function __construct(ArrayGateway $gateway)
|
||||||
|
{
|
||||||
|
parent::__construct($gateway, 'articulos');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testIndexReturnsPaginatedCollection(): void
|
||||||
|
{
|
||||||
|
$response = $this->controller()->render(new JsonRequest(path: '/articulos'));
|
||||||
|
|
||||||
|
self::assertSame(200, $response->status());
|
||||||
|
self::assertSame(2, $response->body()['total']);
|
||||||
|
self::assertSame(1, $response->body()['page']);
|
||||||
|
self::assertSame(20, $response->body()['per_page']);
|
||||||
|
self::assertSame(1, $response->body()['total_pages']);
|
||||||
|
self::assertFalse($response->body()['has_next']);
|
||||||
|
self::assertFalse($response->body()['has_prev']);
|
||||||
|
self::assertCount(2, $response->body()['items']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testPerPageIsClampedToMaximum(): void
|
||||||
|
{
|
||||||
|
$response = $this->controller()->render(new JsonRequest(query: ['per_page' => '99999']));
|
||||||
|
|
||||||
|
self::assertSame(1000, $response->body()['per_page']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testInvalidPageFallsBackToOne(): void
|
||||||
|
{
|
||||||
|
$response = $this->controller()->render(new JsonRequest(query: ['page' => 'abc']));
|
||||||
|
|
||||||
|
self::assertSame(1, $response->body()['page']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testShowReturnsRecord(): void
|
||||||
|
{
|
||||||
|
$response = $this->controller()->render($this->withId('GET', '1'));
|
||||||
|
|
||||||
|
self::assertSame(200, $response->status());
|
||||||
|
self::assertSame('Taladro', $response->body()['nombre']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testShowMissingRecordIs404(): void
|
||||||
|
{
|
||||||
|
$response = $this->controller()->render($this->withId('GET', '99'));
|
||||||
|
|
||||||
|
self::assertSame(404, $response->status());
|
||||||
|
self::assertSame('not_found', $response->body()['code']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testStoreReturns201WithLocation(): void
|
||||||
|
{
|
||||||
|
$response = $this->controller()->render(new JsonRequest(
|
||||||
|
method: 'POST',
|
||||||
|
path: '/articulos',
|
||||||
|
body: ['nombre' => 'Lijadora'],
|
||||||
|
));
|
||||||
|
|
||||||
|
self::assertSame(201, $response->status());
|
||||||
|
self::assertSame('/articulos/3', $response->headers()['Location']);
|
||||||
|
self::assertSame('Lijadora', $response->body()['nombre']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testUpdateReturnsRecord(): void
|
||||||
|
{
|
||||||
|
$response = $this->viaRouter('PUT', '/articulos/1', ['nombre' => 'Taladro Bosch']);
|
||||||
|
|
||||||
|
self::assertSame(200, $response->status());
|
||||||
|
self::assertSame('Taladro Bosch', $response->body()['nombre']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testUpdateMissingIs404(): void
|
||||||
|
{
|
||||||
|
$response = $this->viaRouter('PATCH', '/articulos/99', ['nombre' => 'x']);
|
||||||
|
|
||||||
|
self::assertSame(404, $response->status());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testDestroyReturns204(): void
|
||||||
|
{
|
||||||
|
$response = $this->controller()->render($this->withId('DELETE', '1'));
|
||||||
|
|
||||||
|
self::assertSame(204, $response->status());
|
||||||
|
self::assertNull($response->body());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testDestroyMissingIs404(): void
|
||||||
|
{
|
||||||
|
$response = $this->controller()->render($this->withId('DELETE', '99'));
|
||||||
|
|
||||||
|
self::assertSame(404, $response->status());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testUpdateWithoutIdIs400(): void
|
||||||
|
{
|
||||||
|
$response = $this->controller()->render(new JsonRequest(method: 'PUT', path: '/articulos'));
|
||||||
|
|
||||||
|
self::assertSame(400, $response->status());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testRouterDrivesFullCrudFlow(): void
|
||||||
|
{
|
||||||
|
$router = new Router();
|
||||||
|
$controller = $this->controller();
|
||||||
|
$router->get('/articulos', $controller);
|
||||||
|
$router->post('/articulos', $controller);
|
||||||
|
$router->get('/articulos/{id}', $controller);
|
||||||
|
$router->delete('/articulos/{id}', $controller);
|
||||||
|
|
||||||
|
self::assertSame(
|
||||||
|
2,
|
||||||
|
$router->dispatch(new JsonRequest(path: '/articulos'))->body()['total'],
|
||||||
|
);
|
||||||
|
|
||||||
|
$created = $router->dispatch(new JsonRequest(method: 'POST', path: '/articulos', body: [
|
||||||
|
'nombre' => 'Martillo',
|
||||||
|
]));
|
||||||
|
self::assertSame(201, $created->status());
|
||||||
|
|
||||||
|
$deleted = $router->dispatch(new JsonRequest(method: 'DELETE', path: '/articulos/3'));
|
||||||
|
self::assertSame(204, $deleted->status());
|
||||||
|
|
||||||
|
self::assertSame(
|
||||||
|
2,
|
||||||
|
$router->dispatch(new JsonRequest(path: '/articulos'))->body()['total'],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function withId(string $method, string $id): Request
|
||||||
|
{
|
||||||
|
return (new JsonRequest(method: $method, path: '/articulos/' . $id))->withAttribute(
|
||||||
|
'id',
|
||||||
|
$id,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Drives the request through a real router, so the `{id}` attribute is populated the same way
|
||||||
|
* production does it.
|
||||||
|
*
|
||||||
|
* @param array<string, mixed> $body
|
||||||
|
*/
|
||||||
|
private function viaRouter(string $method, string $path, array $body = []): Response
|
||||||
|
{
|
||||||
|
$router = new Router();
|
||||||
|
$controller = $this->controller();
|
||||||
|
$router->add($method, '/articulos/{id}', $controller);
|
||||||
|
|
||||||
|
return $router->dispatch(new JsonRequest(method: $method, path: $path, body: $body));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Camelia\Controllers\Tests\Unit;
|
||||||
|
|
||||||
|
use Camelia\Controllers\JsonRequest;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
final class JsonRequestTest extends TestCase
|
||||||
|
{
|
||||||
|
public function testReadsInjectedArraysOnly(): void
|
||||||
|
{
|
||||||
|
$request = new JsonRequest(
|
||||||
|
method: 'post',
|
||||||
|
path: '/articulos',
|
||||||
|
query: ['page' => '2'],
|
||||||
|
body: ['nombre' => 'Taladro'],
|
||||||
|
);
|
||||||
|
|
||||||
|
self::assertSame('POST', $request->method());
|
||||||
|
self::assertSame('/articulos', $request->path());
|
||||||
|
self::assertSame('2', $request->query('page'));
|
||||||
|
self::assertSame(['nombre' => 'Taladro'], $request->body());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testQueryFallsBackToDefault(): void
|
||||||
|
{
|
||||||
|
$request = new JsonRequest();
|
||||||
|
|
||||||
|
self::assertNull($request->query('missing'));
|
||||||
|
self::assertSame('x', $request->query('missing', 'x'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testHeaderLookupIsCaseInsensitive(): void
|
||||||
|
{
|
||||||
|
$request = new JsonRequest(headers: ['accept' => 'application/json']);
|
||||||
|
|
||||||
|
self::assertSame('application/json', $request->header('Accept'));
|
||||||
|
self::assertSame('application/json', $request->header('ACCEPT'));
|
||||||
|
self::assertNull($request->header('X-Missing'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testWithAttributeIsImmutable(): void
|
||||||
|
{
|
||||||
|
$original = new JsonRequest(path: '/articulos');
|
||||||
|
$withId = $original->withAttribute('id', '7');
|
||||||
|
|
||||||
|
self::assertNull($original->attribute('id'));
|
||||||
|
self::assertSame('7', $withId->attribute('id'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testWithAttributeKeepsPreviousAttributes(): void
|
||||||
|
{
|
||||||
|
$request = (new JsonRequest())
|
||||||
|
->withAttribute('a', '1')
|
||||||
|
->withAttribute('b', '2');
|
||||||
|
|
||||||
|
self::assertSame('1', $request->attribute('a'));
|
||||||
|
self::assertSame('2', $request->attribute('b'));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Camelia\Controllers\Tests\Unit\Middleware;
|
||||||
|
|
||||||
|
use Camelia\Controllers\JsonRequest;
|
||||||
|
use Camelia\Controllers\Middleware\ContentNegotiation;
|
||||||
|
use Camelia\Controllers\Request;
|
||||||
|
use Camelia\Controllers\Response;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
final class ContentNegotiationTest extends TestCase
|
||||||
|
{
|
||||||
|
private static function ok(Request $request): Response
|
||||||
|
{
|
||||||
|
return new Response(['ok' => true]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testAddsContentType(): void
|
||||||
|
{
|
||||||
|
$response = (new ContentNegotiation())->process(new JsonRequest(), self::ok(...));
|
||||||
|
|
||||||
|
self::assertSame(200, $response->status());
|
||||||
|
self::assertSame('application/json; charset=utf-8', $response->headers()['Content-Type']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testMissingAcceptHeaderIsAccepted(): void
|
||||||
|
{
|
||||||
|
$response = (new ContentNegotiation())->process(new JsonRequest(), self::ok(...));
|
||||||
|
|
||||||
|
self::assertSame(200, $response->status());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testJsonAcceptIsAccepted(): void
|
||||||
|
{
|
||||||
|
$response = (new ContentNegotiation())->process(
|
||||||
|
new JsonRequest(headers: ['accept' => 'application/json']),
|
||||||
|
self::ok(...),
|
||||||
|
);
|
||||||
|
|
||||||
|
self::assertSame(200, $response->status());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testBrowserAcceptIsAccepted(): void
|
||||||
|
{
|
||||||
|
$accept = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
|
||||||
|
|
||||||
|
$response = (new ContentNegotiation())->process(
|
||||||
|
new JsonRequest(headers: ['accept' => $accept]),
|
||||||
|
self::ok(...),
|
||||||
|
);
|
||||||
|
|
||||||
|
self::assertSame(200, $response->status());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testIncompatibleAcceptIs406(): void
|
||||||
|
{
|
||||||
|
$response = (new ContentNegotiation())->process(
|
||||||
|
new JsonRequest(headers: ['accept' => 'application/xml']),
|
||||||
|
static function (): Response {
|
||||||
|
self::fail('The handler must not run when the client rejects JSON.');
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
self::assertSame(406, $response->status());
|
||||||
|
self::assertSame('not_acceptable', $response->body()['code']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testZeroQualityIsRejected(): void
|
||||||
|
{
|
||||||
|
$response = (new ContentNegotiation())->process(
|
||||||
|
new JsonRequest(headers: ['accept' => 'application/json;q=0']),
|
||||||
|
static function (): Response {
|
||||||
|
self::fail('A q=0 entry means not acceptable.');
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
self::assertSame(406, $response->status());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testNonZeroQualityIsAccepted(): void
|
||||||
|
{
|
||||||
|
$response = (new ContentNegotiation())->process(
|
||||||
|
new JsonRequest(headers: ['accept' => 'application/json;q=0.5']),
|
||||||
|
self::ok(...),
|
||||||
|
);
|
||||||
|
|
||||||
|
self::assertSame(200, $response->status());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testExistingContentTypeIsPreserved(): void
|
||||||
|
{
|
||||||
|
$response = (new ContentNegotiation())->process(
|
||||||
|
new JsonRequest(),
|
||||||
|
static fn(): Response => new Response(['ok' => true], 200, [
|
||||||
|
'Content-Type' => 'application/problem+json',
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
self::assertSame('application/problem+json', $response->headers()['Content-Type']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testContentTypeCanBeDisabled(): void
|
||||||
|
{
|
||||||
|
$response = (new ContentNegotiation(addContentType: false))->process(
|
||||||
|
new JsonRequest(),
|
||||||
|
self::ok(...),
|
||||||
|
);
|
||||||
|
|
||||||
|
self::assertFalse($response->hasHeader('Content-Type'));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Camelia\Controllers\Tests\Unit\Middleware;
|
||||||
|
|
||||||
|
use Camelia\Controllers\JsonRequest;
|
||||||
|
use Camelia\Controllers\Middleware\Logging;
|
||||||
|
use Camelia\Controllers\Request;
|
||||||
|
use Camelia\Controllers\Response;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
final class LoggingTest extends TestCase
|
||||||
|
{
|
||||||
|
/** @var list<array{level: string, message: string, context: array<string, mixed>}> */
|
||||||
|
private array $logs = [];
|
||||||
|
|
||||||
|
private float $now = 100.0;
|
||||||
|
|
||||||
|
private function logging(): Logging
|
||||||
|
{
|
||||||
|
return new Logging(
|
||||||
|
function (string $level, string $message, array $context): void {
|
||||||
|
$this->logs[] = ['level' => $level, 'message' => $message, 'context' => $context];
|
||||||
|
},
|
||||||
|
fn(): float => $this->now,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function ok(Request $request): Response
|
||||||
|
{
|
||||||
|
return new Response(['ok' => true]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testRecordsSuccessfulRequest(): void
|
||||||
|
{
|
||||||
|
$response = $this->logging()->process(
|
||||||
|
new JsonRequest(method: 'GET', path: '/articulos'),
|
||||||
|
self::ok(...),
|
||||||
|
);
|
||||||
|
|
||||||
|
self::assertSame(200, $response->status());
|
||||||
|
self::assertCount(1, $this->logs);
|
||||||
|
self::assertSame('info', $this->logs[0]['level']);
|
||||||
|
self::assertSame('GET /articulos 200', $this->logs[0]['message']);
|
||||||
|
self::assertSame('/articulos', $this->logs[0]['context']['path']);
|
||||||
|
self::assertSame(200, $this->logs[0]['context']['status']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testClientErrorLogsWarning(): void
|
||||||
|
{
|
||||||
|
$this->logging()->process(
|
||||||
|
new JsonRequest(path: '/x'),
|
||||||
|
static fn(): Response => new Response(['e' => 1], 404),
|
||||||
|
);
|
||||||
|
|
||||||
|
self::assertSame('warning', $this->logs[0]['level']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testServerErrorLogsError(): void
|
||||||
|
{
|
||||||
|
$this->logging()->process(
|
||||||
|
new JsonRequest(path: '/x'),
|
||||||
|
static fn(): Response => new Response(null, 500),
|
||||||
|
);
|
||||||
|
|
||||||
|
self::assertSame('error', $this->logs[0]['level']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testDurationIsMeasured(): void
|
||||||
|
{
|
||||||
|
$reads = [100.0, 120.5, 120.5, 163.0];
|
||||||
|
$logging = new Logging(function (string $level, string $message, array $context): void {
|
||||||
|
$this->logs[] = ['level' => $level, 'message' => $message, 'context' => $context];
|
||||||
|
}, static function () use (&$reads): float {
|
||||||
|
return (float) array_shift($reads);
|
||||||
|
});
|
||||||
|
|
||||||
|
$logging->process(new JsonRequest(), static fn(): Response => new Response(null));
|
||||||
|
self::assertSame(20.5, $this->logs[0]['context']['duration_ms']);
|
||||||
|
|
||||||
|
$logging->process(new JsonRequest(), static fn(): Response => new Response(null));
|
||||||
|
self::assertSame(42.5, $this->logs[1]['context']['duration_ms']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testThrowableIsLoggedAndRethrown(): void
|
||||||
|
{
|
||||||
|
$logging = $this->logging();
|
||||||
|
|
||||||
|
try {
|
||||||
|
$logging->process(new JsonRequest(path: '/boom'), static function (): Response {
|
||||||
|
throw new \RuntimeException('exploded');
|
||||||
|
});
|
||||||
|
|
||||||
|
self::fail('The exception must propagate: the router owns error mapping.');
|
||||||
|
} catch (\RuntimeException $exception) {
|
||||||
|
self::assertSame('exploded', $exception->getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
self::assertCount(1, $this->logs);
|
||||||
|
self::assertSame(500, $this->logs[0]['context']['status']);
|
||||||
|
self::assertSame('error', $this->logs[0]['level']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testReturnsHandlerResponseUnchanged(): void
|
||||||
|
{
|
||||||
|
$original = new Response(['x' => 1], 201, ['Location' => '/a/1']);
|
||||||
|
|
||||||
|
$response = $this->logging()->process(
|
||||||
|
new JsonRequest(),
|
||||||
|
static fn(): Response => $original,
|
||||||
|
);
|
||||||
|
|
||||||
|
self::assertSame($original, $response);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Camelia\Controllers\Tests\Unit;
|
||||||
|
|
||||||
|
use Camelia\Controllers\JsonRequest;
|
||||||
|
use Camelia\Controllers\Middleware;
|
||||||
|
use Camelia\Controllers\Pipeline;
|
||||||
|
use Camelia\Controllers\Request;
|
||||||
|
use Camelia\Controllers\Response;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
final class PipelineTest extends TestCase
|
||||||
|
{
|
||||||
|
public function testRunsHandlerWhenEmpty(): void
|
||||||
|
{
|
||||||
|
$pipeline = new Pipeline();
|
||||||
|
|
||||||
|
$response = $pipeline->process(
|
||||||
|
new JsonRequest(),
|
||||||
|
static fn(): Response => new Response(['ok' => true]),
|
||||||
|
);
|
||||||
|
|
||||||
|
self::assertSame(['ok' => true], $response->body());
|
||||||
|
self::assertTrue($pipeline->isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testRunsMiddlewaresOutsideIn(): void
|
||||||
|
{
|
||||||
|
$order = [];
|
||||||
|
$first = new Recorder('first', $order);
|
||||||
|
$second = new Recorder('second', $order);
|
||||||
|
|
||||||
|
$pipeline = new Pipeline([$first, $second]);
|
||||||
|
$pipeline->process(new JsonRequest(), static function (Request $request) use (
|
||||||
|
&$order,
|
||||||
|
): Response {
|
||||||
|
$order[] = 'handler';
|
||||||
|
|
||||||
|
return new Response(null);
|
||||||
|
});
|
||||||
|
|
||||||
|
self::assertSame(
|
||||||
|
['first:before', 'second:before', 'handler', 'second:after', 'first:after'],
|
||||||
|
$order,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testMiddlewareCanShortCircuit(): void
|
||||||
|
{
|
||||||
|
$blocked = new class implements Middleware {
|
||||||
|
public function process(Request $request, callable $next): Response
|
||||||
|
{
|
||||||
|
return new Response(['blocked' => true], 403);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
$pipeline = new Pipeline([$blocked]);
|
||||||
|
$response = $pipeline->process(new JsonRequest(), static function (): Response {
|
||||||
|
self::fail('The handler must not run when a middleware short-circuits.');
|
||||||
|
});
|
||||||
|
|
||||||
|
self::assertSame(403, $response->status());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testWithReturnsCopy(): void
|
||||||
|
{
|
||||||
|
$order = [];
|
||||||
|
$base = new Pipeline();
|
||||||
|
$withOne = $base->with(new Recorder('x', $order));
|
||||||
|
|
||||||
|
self::assertTrue($base->isEmpty());
|
||||||
|
self::assertCount(1, $withOne->middlewares());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final class Recorder implements Middleware
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* The array is shared by reference with the test, so appending to it is the only operation.
|
||||||
|
*
|
||||||
|
* @param list<string> $order Passed by reference so the test observes the shared log.
|
||||||
|
*/
|
||||||
|
public function __construct(
|
||||||
|
private readonly string $name,
|
||||||
|
/** @phpstan-ignore property.onlyWritten */
|
||||||
|
private array &$order,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function process(Request $request, callable $next): Response
|
||||||
|
{
|
||||||
|
$this->order[] = $this->name . ':before';
|
||||||
|
$response = $next($request);
|
||||||
|
$this->order[] = $this->name . ':after';
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Camelia\Controllers\Tests\Unit;
|
||||||
|
|
||||||
|
use Camelia\Controllers\Exception\BadRequest;
|
||||||
|
use Camelia\Controllers\Exception\NotFound;
|
||||||
|
use Camelia\Controllers\Exception\ServerError;
|
||||||
|
use Camelia\Controllers\Exception\ValidationFailed;
|
||||||
|
use Camelia\Controllers\Response;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
final class ResponseTest extends TestCase
|
||||||
|
{
|
||||||
|
public function testBodyAndStatus(): void
|
||||||
|
{
|
||||||
|
$response = new Response(['ok' => true], 201);
|
||||||
|
|
||||||
|
self::assertSame(['ok' => true], $response->body());
|
||||||
|
self::assertSame(201, $response->status());
|
||||||
|
self::assertTrue($response->isSuccessful());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testNoContentHasNoBody(): void
|
||||||
|
{
|
||||||
|
$response = Response::noContent();
|
||||||
|
|
||||||
|
self::assertSame(204, $response->status());
|
||||||
|
self::assertNull($response->body());
|
||||||
|
self::assertSame('', $response->toJson());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testToJsonKeepsUnicodeAndSlashes(): void
|
||||||
|
{
|
||||||
|
$response = new Response(['nombre' => 'Taladro Ñ', 'url' => '/a/b']);
|
||||||
|
|
||||||
|
self::assertSame('{"nombre":"Taladro Ñ","url":"/a/b"}', $response->toJson());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testWithHeaderReturnsCopy(): void
|
||||||
|
{
|
||||||
|
$original = new Response(['ok' => true]);
|
||||||
|
$modified = $original->withHeader('X-Trace', 'abc');
|
||||||
|
|
||||||
|
self::assertFalse($original->hasHeader('X-Trace'));
|
||||||
|
self::assertTrue($modified->hasHeader('X-Trace'));
|
||||||
|
self::assertSame('abc', $modified->headers()['X-Trace']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testHttpErrorsExposeStatusAndCode(): void
|
||||||
|
{
|
||||||
|
$notFound = new NotFound('missing');
|
||||||
|
self::assertSame(404, $notFound->status());
|
||||||
|
self::assertSame('not_found', $notFound->errorCode());
|
||||||
|
|
||||||
|
$badRequest = new BadRequest();
|
||||||
|
self::assertSame(400, $badRequest->status());
|
||||||
|
|
||||||
|
$serverError = ServerError::fromThrowable(new \RuntimeException('secret detail'));
|
||||||
|
self::assertSame(500, $serverError->status());
|
||||||
|
self::assertSame('An unexpected error occurred.', $serverError->getMessage());
|
||||||
|
self::assertStringNotContainsString(
|
||||||
|
'secret',
|
||||||
|
(string) json_encode($serverError->toArray()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testValidationFailedCarriesFieldErrors(): void
|
||||||
|
{
|
||||||
|
$error = new ValidationFailed(['nombre' => ['Required.']]);
|
||||||
|
$payload = $error->toArray();
|
||||||
|
|
||||||
|
self::assertSame(422, $error->status());
|
||||||
|
self::assertSame(['nombre' => ['Required.']], $payload['errors']);
|
||||||
|
self::assertSame('validation_failed', $payload['code']);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Camelia\Controllers\Tests\Unit;
|
||||||
|
|
||||||
|
use Camelia\Controllers\Controller;
|
||||||
|
use Camelia\Controllers\Request;
|
||||||
|
use Camelia\Controllers\Response;
|
||||||
|
use Camelia\Controllers\Route;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
final class RouteTest extends TestCase
|
||||||
|
{
|
||||||
|
public function testMatchesStaticPath(): void
|
||||||
|
{
|
||||||
|
$route = new Route('GET', '/articulos', new NoopController());
|
||||||
|
|
||||||
|
self::assertSame([], $route->matches('/articulos'));
|
||||||
|
self::assertNull($route->matches('/clientes'));
|
||||||
|
self::assertNull($route->matches('/articulos/7'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testCapturesParameters(): void
|
||||||
|
{
|
||||||
|
$route = new Route('GET', '/articulos/{id}', new NoopController());
|
||||||
|
|
||||||
|
self::assertSame(['id' => '7'], $route->matches('/articulos/7'));
|
||||||
|
self::assertSame(['id' => 'abc'], $route->matches('/articulos/abc'));
|
||||||
|
self::assertNull($route->matches('/articulos'));
|
||||||
|
self::assertNull($route->matches('/articulos/7/detalle'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testCapturesMultipleParameters(): void
|
||||||
|
{
|
||||||
|
$route = new Route(
|
||||||
|
'GET',
|
||||||
|
'/facturas/{facturaId}/detalles/{detalleId}',
|
||||||
|
new NoopController(),
|
||||||
|
);
|
||||||
|
|
||||||
|
self::assertSame(
|
||||||
|
['facturaId' => '3', 'detalleId' => '9'],
|
||||||
|
$route->matches('/facturas/3/detalles/9'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testLiteralDotsAreEscaped(): void
|
||||||
|
{
|
||||||
|
$route = new Route('GET', '/archivos/reporte.json', new NoopController());
|
||||||
|
|
||||||
|
self::assertSame([], $route->matches('/archivos/reporte.json'));
|
||||||
|
self::assertNull($route->matches('/archivos/reporteXjson'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testParameterNamesAreExposed(): void
|
||||||
|
{
|
||||||
|
$route = new Route('POST', '/a/{uno}/b/{dos}', new NoopController());
|
||||||
|
|
||||||
|
self::assertSame(['uno', 'dos'], $route->parameters());
|
||||||
|
self::assertSame('POST', $route->method());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final class NoopController extends Controller
|
||||||
|
{
|
||||||
|
public function render(Request $request): Response
|
||||||
|
{
|
||||||
|
return Response::noContent();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Camelia\Controllers\Tests\Unit;
|
||||||
|
|
||||||
|
use Camelia\Controllers\Controller;
|
||||||
|
use Camelia\Controllers\Exception\NotFound;
|
||||||
|
use Camelia\Controllers\JsonRequest;
|
||||||
|
use Camelia\Controllers\Request;
|
||||||
|
use Camelia\Controllers\Response;
|
||||||
|
use Camelia\Controllers\Router;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
final class RouterTest extends TestCase
|
||||||
|
{
|
||||||
|
public function testDispatchesToController(): void
|
||||||
|
{
|
||||||
|
$router = new Router();
|
||||||
|
$router->get('/articulos/{id}', new FixedController(['id' => 'seen'], 200));
|
||||||
|
|
||||||
|
$response = $router->dispatch(new JsonRequest(path: '/articulos/7'));
|
||||||
|
|
||||||
|
self::assertSame(200, $response->status());
|
||||||
|
self::assertSame(['id' => 'seen'], $response->body());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testHandlerReceivesRouteAttribute(): void
|
||||||
|
{
|
||||||
|
$router = new Router();
|
||||||
|
$router->get(
|
||||||
|
'/articulos/{id}',
|
||||||
|
static fn(Request $r): Response => new Response([
|
||||||
|
'id' => $r->attribute('id'),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
$response = $router->dispatch(new JsonRequest(path: '/articulos/42'));
|
||||||
|
|
||||||
|
self::assertSame(['id' => '42'], $response->body());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testUnknownPathIs404(): void
|
||||||
|
{
|
||||||
|
$router = new Router();
|
||||||
|
$router->get('/articulos', new FixedController([], 200));
|
||||||
|
|
||||||
|
$response = $router->dispatch(new JsonRequest(path: '/clientes'));
|
||||||
|
|
||||||
|
self::assertSame(404, $response->status());
|
||||||
|
self::assertSame('not_found', $response->body()['code']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testWrongMethodIs405WithAllowHeader(): void
|
||||||
|
{
|
||||||
|
$router = new Router();
|
||||||
|
$router->get('/articulos', new FixedController([], 200));
|
||||||
|
$router->post('/articulos', new FixedController([], 201));
|
||||||
|
|
||||||
|
$response = $router->dispatch(new JsonRequest(method: 'DELETE', path: '/articulos'));
|
||||||
|
|
||||||
|
self::assertSame(405, $response->status());
|
||||||
|
self::assertSame('method_not_allowed', $response->body()['code']);
|
||||||
|
self::assertSame('GET, POST, HEAD', $response->headers()['Allow']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testHttpErrorThrownByHandlerBecomesResponse(): void
|
||||||
|
{
|
||||||
|
$router = new Router();
|
||||||
|
$router->get('/x', static function (): Response {
|
||||||
|
throw NotFound::route('/x');
|
||||||
|
});
|
||||||
|
|
||||||
|
$response = $router->dispatch(new JsonRequest(path: '/x'));
|
||||||
|
|
||||||
|
self::assertSame(404, $response->status());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testUnexpectedThrowableBecomes500WithoutLeakingDetail(): void
|
||||||
|
{
|
||||||
|
$router = new Router();
|
||||||
|
$router->get('/x', static function (): Response {
|
||||||
|
throw new \RuntimeException('internal detail');
|
||||||
|
});
|
||||||
|
|
||||||
|
$response = $router->dispatch(new JsonRequest(path: '/x'));
|
||||||
|
|
||||||
|
self::assertSame(500, $response->status());
|
||||||
|
self::assertSame('server_error', $response->body()['code']);
|
||||||
|
self::assertStringNotContainsString('internal detail', $response->toJson());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testVerbsAreChainable(): void
|
||||||
|
{
|
||||||
|
$router = new Router();
|
||||||
|
$controller = new FixedController([], 200);
|
||||||
|
|
||||||
|
self::assertSame($router, $router->get('/a', $controller)->post('/a', $controller));
|
||||||
|
self::assertCount(2, $router->routes());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final class FixedController extends Controller
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly mixed $payload,
|
||||||
|
private readonly int $status,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function render(Request $request): Response
|
||||||
|
{
|
||||||
|
return new Response($this->payload, $this->status);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Camelia\Controllers\Tests\Unit\Security;
|
||||||
|
|
||||||
|
use Camelia\Controllers\Exception\BadRequest;
|
||||||
|
use Camelia\Controllers\JsonRequest;
|
||||||
|
use Camelia\Controllers\Request;
|
||||||
|
use Camelia\Controllers\Response;
|
||||||
|
use Camelia\Controllers\Router;
|
||||||
|
use Camelia\Controllers\Security\BearerAuth;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
final class BearerAuthTest extends TestCase
|
||||||
|
{
|
||||||
|
private static function passThrough(Request $request): Response
|
||||||
|
{
|
||||||
|
return new Response(['ok' => true]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testMissingHeaderIs401(): void
|
||||||
|
{
|
||||||
|
$auth = new BearerAuth(static fn(string $token): array => ['id' => 1]);
|
||||||
|
|
||||||
|
$response = $auth->process(new JsonRequest(), self::passThrough(...));
|
||||||
|
|
||||||
|
self::assertSame(401, $response->status());
|
||||||
|
self::assertSame('unauthorized', $response->body()['code']);
|
||||||
|
self::assertSame('Bearer', $response->headers()['WWW-Authenticate']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testNonBearerSchemeIs401(): void
|
||||||
|
{
|
||||||
|
$auth = new BearerAuth(static fn(string $token): array => ['id' => 1]);
|
||||||
|
|
||||||
|
$response = $auth->process(
|
||||||
|
new JsonRequest(headers: ['authorization' => 'Basic dXNlcjpwYXNz']),
|
||||||
|
self::passThrough(...),
|
||||||
|
);
|
||||||
|
|
||||||
|
self::assertSame(401, $response->status());
|
||||||
|
self::assertStringContainsString('Bearer scheme', $response->body()['message']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testInvalidTokenIs401(): void
|
||||||
|
{
|
||||||
|
$auth = new BearerAuth(static fn(string $token): ?array => null);
|
||||||
|
|
||||||
|
$response = $auth->process(
|
||||||
|
new JsonRequest(headers: ['authorization' => 'Bearer expired']),
|
||||||
|
self::passThrough(...),
|
||||||
|
);
|
||||||
|
|
||||||
|
self::assertSame(401, $response->status());
|
||||||
|
self::assertStringContainsString('invalid or expired', $response->body()['message']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testValidTokenAttachesIdentity(): void
|
||||||
|
{
|
||||||
|
$auth = new BearerAuth(static fn(string $token): array => [
|
||||||
|
'id' => 7,
|
||||||
|
'roles' => ['admin'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$response = $auth->process(
|
||||||
|
new JsonRequest(headers: ['authorization' => 'Bearer good-token']),
|
||||||
|
static function (Request $request): Response {
|
||||||
|
return new Response($request->attribute(BearerAuth::ATTRIBUTE));
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
self::assertSame(200, $response->status());
|
||||||
|
self::assertSame(['id' => 7, 'roles' => ['admin']], $response->body());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testSchemeIsCaseInsensitive(): void
|
||||||
|
{
|
||||||
|
$auth = new BearerAuth(static fn(string $token): array => ['id' => 1]);
|
||||||
|
|
||||||
|
$response = $auth->process(
|
||||||
|
new JsonRequest(headers: ['authorization' => 'bearer abc']),
|
||||||
|
self::passThrough(...),
|
||||||
|
);
|
||||||
|
|
||||||
|
self::assertSame(200, $response->status());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testRouterRejectsBeforeReachingController(): void
|
||||||
|
{
|
||||||
|
$router = (new Router())->withMiddleware(
|
||||||
|
new BearerAuth(static fn(string $token): ?array => null),
|
||||||
|
);
|
||||||
|
$router->get('/x', static fn(): Response => new Response(['leaked' => true]));
|
||||||
|
|
||||||
|
$response = $router->dispatch(new JsonRequest(path: '/x'));
|
||||||
|
|
||||||
|
self::assertSame(401, $response->status());
|
||||||
|
self::assertStringNotContainsString('leaked', $response->toJson());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testRouterAllowsValidToken(): void
|
||||||
|
{
|
||||||
|
$router = (new Router())->withMiddleware(new BearerAuth(static fn(string $token): array => [
|
||||||
|
'id' => 1,
|
||||||
|
]));
|
||||||
|
$router->get(
|
||||||
|
'/x',
|
||||||
|
static fn(Request $request): Response => new Response($request->attribute(
|
||||||
|
BearerAuth::ATTRIBUTE,
|
||||||
|
)),
|
||||||
|
);
|
||||||
|
|
||||||
|
$response = $router->dispatch(new JsonRequest(path: '/x', headers: [
|
||||||
|
'authorization' => 'Bearer t',
|
||||||
|
]));
|
||||||
|
|
||||||
|
self::assertSame(200, $response->status());
|
||||||
|
self::assertSame(['id' => 1], $response->body());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testEmptyRoleListIsRejectedAtConstruction(): void
|
||||||
|
{
|
||||||
|
$this->expectException(BadRequest::class);
|
||||||
|
|
||||||
|
new \Camelia\Controllers\Security\RequireRole([]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Camelia\Controllers\Tests\Unit\Security;
|
||||||
|
|
||||||
|
use Camelia\Controllers\JsonRequest;
|
||||||
|
use Camelia\Controllers\Request;
|
||||||
|
use Camelia\Controllers\Response;
|
||||||
|
use Camelia\Controllers\Security\Cors;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
final class CorsTest extends TestCase
|
||||||
|
{
|
||||||
|
private static function passThrough(Request $request): Response
|
||||||
|
{
|
||||||
|
return new Response(['ok' => true]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testPreflightIsAnsweredWithoutHandler(): void
|
||||||
|
{
|
||||||
|
$cors = new Cors();
|
||||||
|
|
||||||
|
$response = $cors->process(
|
||||||
|
new JsonRequest(method: 'OPTIONS', headers: ['origin' => 'https://app.test']),
|
||||||
|
static function (): Response {
|
||||||
|
self::fail('A preflight must not reach the handler.');
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
self::assertSame(204, $response->status());
|
||||||
|
self::assertSame('*', $response->headers()['Access-Control-Allow-Origin']);
|
||||||
|
self::assertStringContainsString(
|
||||||
|
'PATCH',
|
||||||
|
$response->headers()['Access-Control-Allow-Methods'],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testWildcardOriginIsAddedToResponse(): void
|
||||||
|
{
|
||||||
|
$response = (new Cors())->process(
|
||||||
|
new JsonRequest(headers: ['origin' => 'https://app.test']),
|
||||||
|
self::passThrough(...),
|
||||||
|
);
|
||||||
|
|
||||||
|
self::assertSame(200, $response->status());
|
||||||
|
self::assertSame('*', $response->headers()['Access-Control-Allow-Origin']);
|
||||||
|
self::assertSame('Origin', $response->headers()['Vary']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testDisallowedOriginGetsNoAllowOrigin(): void
|
||||||
|
{
|
||||||
|
$cors = new Cors(allowedOrigins: ['https://app.test']);
|
||||||
|
|
||||||
|
$response = $cors->process(
|
||||||
|
new JsonRequest(headers: ['origin' => 'https://evil.test']),
|
||||||
|
self::passThrough(...),
|
||||||
|
);
|
||||||
|
|
||||||
|
self::assertFalse($response->hasHeader('Access-Control-Allow-Origin'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testAllowedOriginIsEchoed(): void
|
||||||
|
{
|
||||||
|
$cors = new Cors(allowedOrigins: ['https://app.test']);
|
||||||
|
|
||||||
|
$response = $cors->process(
|
||||||
|
new JsonRequest(headers: ['origin' => 'https://app.test']),
|
||||||
|
self::passThrough(...),
|
||||||
|
);
|
||||||
|
|
||||||
|
self::assertSame('https://app.test', $response->headers()['Access-Control-Allow-Origin']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testCredentialsWithWildcardEchoesOriginInstead(): void
|
||||||
|
{
|
||||||
|
$cors = new Cors(allowedOrigins: ['*'], allowCredentials: true);
|
||||||
|
|
||||||
|
$response = $cors->process(
|
||||||
|
new JsonRequest(headers: ['origin' => 'https://app.test']),
|
||||||
|
self::passThrough(...),
|
||||||
|
);
|
||||||
|
|
||||||
|
// `*` plus credentials is rejected by browsers, so the exact origin must be echoed.
|
||||||
|
self::assertSame('https://app.test', $response->headers()['Access-Control-Allow-Origin']);
|
||||||
|
self::assertSame('true', $response->headers()['Access-Control-Allow-Credentials']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testCredentialsWithoutOriginSendsNoAllowOrigin(): void
|
||||||
|
{
|
||||||
|
$cors = new Cors(allowedOrigins: ['*'], allowCredentials: true);
|
||||||
|
|
||||||
|
$response = $cors->process(new JsonRequest(), self::passThrough(...));
|
||||||
|
|
||||||
|
self::assertFalse($response->hasHeader('Access-Control-Allow-Origin'));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Camelia\Controllers\Tests\Unit\Security;
|
||||||
|
|
||||||
|
use Camelia\Controllers\JsonRequest;
|
||||||
|
use Camelia\Controllers\Request;
|
||||||
|
use Camelia\Controllers\Response;
|
||||||
|
use Camelia\Controllers\Security\RateLimit;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
final class RateLimitTest extends TestCase
|
||||||
|
{
|
||||||
|
private int $now = 1000;
|
||||||
|
|
||||||
|
private static function passThrough(Request $request): Response
|
||||||
|
{
|
||||||
|
return new Response(['ok' => true], 200, ['X-Custom' => 'kept']);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function limiter(int $limit = 3, int $window = 60): RateLimit
|
||||||
|
{
|
||||||
|
return new RateLimit(limit: $limit, windowSeconds: $window, clock: fn(): int => $this->now);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testAllowsUpToLimit(): void
|
||||||
|
{
|
||||||
|
$limiter = $this->limiter(3);
|
||||||
|
|
||||||
|
for ($i = 1; $i <= 3; ++$i) {
|
||||||
|
self::assertSame(
|
||||||
|
200,
|
||||||
|
$limiter->process(new JsonRequest(), self::passThrough(...))->status(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testExceedingLimitIs429(): void
|
||||||
|
{
|
||||||
|
$limiter = $this->limiter(2);
|
||||||
|
|
||||||
|
$limiter->process(new JsonRequest(), self::passThrough(...));
|
||||||
|
$limiter->process(new JsonRequest(), self::passThrough(...));
|
||||||
|
$response = $limiter->process(new JsonRequest(), self::passThrough(...));
|
||||||
|
|
||||||
|
self::assertSame(429, $response->status());
|
||||||
|
self::assertSame('too_many_requests', $response->body()['code']);
|
||||||
|
self::assertSame('60', $response->headers()['Retry-After']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testHeadersPresentOnSuccess(): void
|
||||||
|
{
|
||||||
|
$response = $this->limiter(10)->process(new JsonRequest(), self::passThrough(...));
|
||||||
|
|
||||||
|
self::assertSame('10', $response->headers()['X-RateLimit-Limit']);
|
||||||
|
self::assertSame('9', $response->headers()['X-RateLimit-Remaining']);
|
||||||
|
self::assertSame('1060', $response->headers()['X-RateLimit-Reset']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testKeepsHandlerHeaders(): void
|
||||||
|
{
|
||||||
|
$response = $this->limiter(10)->process(new JsonRequest(), self::passThrough(...));
|
||||||
|
|
||||||
|
self::assertSame('kept', $response->headers()['X-Custom']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testWindowResetsAfterExpiry(): void
|
||||||
|
{
|
||||||
|
$limiter = $this->limiter(1);
|
||||||
|
|
||||||
|
self::assertSame(
|
||||||
|
200,
|
||||||
|
$limiter->process(new JsonRequest(), self::passThrough(...))->status(),
|
||||||
|
);
|
||||||
|
self::assertSame(
|
||||||
|
429,
|
||||||
|
$limiter->process(new JsonRequest(), self::passThrough(...))->status(),
|
||||||
|
);
|
||||||
|
|
||||||
|
$this->now += 61;
|
||||||
|
|
||||||
|
self::assertSame(
|
||||||
|
200,
|
||||||
|
$limiter->process(new JsonRequest(), self::passThrough(...))->status(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testBucketsAreSeparatedByClientAddress(): void
|
||||||
|
{
|
||||||
|
$limiter = $this->limiter(1);
|
||||||
|
$first = (new JsonRequest())->withAttribute('client_ip', '10.0.0.1');
|
||||||
|
$second = (new JsonRequest())->withAttribute('client_ip', '10.0.0.2');
|
||||||
|
|
||||||
|
self::assertSame(200, $limiter->process($first, self::passThrough(...))->status());
|
||||||
|
self::assertSame(200, $limiter->process($second, self::passThrough(...))->status());
|
||||||
|
self::assertSame(429, $limiter->process($first, self::passThrough(...))->status());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testResetInReportsRemainingWindow(): void
|
||||||
|
{
|
||||||
|
$limiter = $this->limiter(1);
|
||||||
|
$request = new JsonRequest();
|
||||||
|
|
||||||
|
self::assertSame(0, $limiter->resetIn($request));
|
||||||
|
|
||||||
|
$limiter->process($request, self::passThrough(...));
|
||||||
|
self::assertSame(60, $limiter->resetIn($request));
|
||||||
|
|
||||||
|
$this->now += 20;
|
||||||
|
self::assertSame(40, $limiter->resetIn($request));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Camelia\Controllers\Tests\Unit\Security;
|
||||||
|
|
||||||
|
use Camelia\Controllers\JsonRequest;
|
||||||
|
use Camelia\Controllers\Request;
|
||||||
|
use Camelia\Controllers\Response;
|
||||||
|
use Camelia\Controllers\Security\RequireRole;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
final class RequireRoleTest extends TestCase
|
||||||
|
{
|
||||||
|
private static function passThrough(Request $request): Response
|
||||||
|
{
|
||||||
|
return new Response(['ok' => true]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function withUser(mixed $user): Request
|
||||||
|
{
|
||||||
|
return (new JsonRequest())->withAttribute('user', $user);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testNoIdentityIs401(): void
|
||||||
|
{
|
||||||
|
$response = (new RequireRole(['admin']))->process(
|
||||||
|
new JsonRequest(),
|
||||||
|
self::passThrough(...),
|
||||||
|
);
|
||||||
|
|
||||||
|
self::assertSame(401, $response->status());
|
||||||
|
self::assertStringContainsString(
|
||||||
|
'Authentication is required',
|
||||||
|
$response->body()['message'],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testMissingRoleIs401(): void
|
||||||
|
{
|
||||||
|
$middleware = new RequireRole(['admin']);
|
||||||
|
|
||||||
|
$response = $middleware->process(
|
||||||
|
self::withUser(['id' => 1, 'roles' => ['vendedor']]),
|
||||||
|
self::passThrough(...),
|
||||||
|
);
|
||||||
|
|
||||||
|
self::assertSame(401, $response->status());
|
||||||
|
self::assertStringContainsString('admin', $response->body()['message']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testGrantedRolePasses(): void
|
||||||
|
{
|
||||||
|
$middleware = new RequireRole(['admin', 'gerente']);
|
||||||
|
|
||||||
|
$response = $middleware->process(
|
||||||
|
self::withUser(['id' => 1, 'roles' => ['gerente']]),
|
||||||
|
self::passThrough(...),
|
||||||
|
);
|
||||||
|
|
||||||
|
self::assertSame(200, $response->status());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testSingleRoleStringIsAccepted(): void
|
||||||
|
{
|
||||||
|
$middleware = new RequireRole(['admin']);
|
||||||
|
|
||||||
|
$response = $middleware->process(
|
||||||
|
self::withUser(['role' => 'admin']),
|
||||||
|
self::passThrough(...),
|
||||||
|
);
|
||||||
|
|
||||||
|
self::assertSame(200, $response->status());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testMalformedRolesFailClosed(): void
|
||||||
|
{
|
||||||
|
$middleware = new RequireRole(['admin']);
|
||||||
|
|
||||||
|
$response = $middleware->process(
|
||||||
|
self::withUser(['roles' => 'admin']),
|
||||||
|
self::passThrough(...),
|
||||||
|
);
|
||||||
|
|
||||||
|
// A string is a valid single role; the point is that no exception escapes.
|
||||||
|
self::assertSame(200, $response->status());
|
||||||
|
|
||||||
|
$broken = $middleware->process(
|
||||||
|
self::withUser(['roles' => [42, null]]),
|
||||||
|
self::passThrough(...),
|
||||||
|
);
|
||||||
|
self::assertSame(401, $broken->status());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testIdentityMustBeArray(): void
|
||||||
|
{
|
||||||
|
$middleware = new RequireRole(['admin']);
|
||||||
|
|
||||||
|
$response = $middleware->process(self::withUser('admin'), self::passThrough(...));
|
||||||
|
|
||||||
|
self::assertSame(401, $response->status());
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user