commit 341d1bdc2c5140ec4040549ebff15997fce3bc28 Author: Dario Garcia Date: Sun Nov 15 10:14:27 2026 -0300 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. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d767177 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +/vendor/ +.phpunit.cache/ +.phpunit.result.cache +.mago.cache +coverage/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..6ebcb17 --- /dev/null +++ b/AGENTS.md @@ -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. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..5082191 --- /dev/null +++ b/LICENSE @@ -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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..580e33f --- /dev/null +++ b/README.md @@ -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). diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..869ce8d --- /dev/null +++ b/composer.json @@ -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" + } + } +} diff --git a/composer.lock b/composer.lock new file mode 100644 index 0000000..7eecf79 --- /dev/null +++ b/composer.lock @@ -0,0 +1,1975 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", + "This file is @generated automatically" + ], + "content-hash": "c828e25914c9dd9e5cf7667b446f40ad", + "packages": [], + "packages-dev": [ + { + "name": "carthage-software/mago", + "version": "1.60.1", + "source": { + "type": "git", + "url": "https://github.com/carthage-software/mago.git", + "reference": "4f64a85e4b4c5632eae895a8d8564898ffcaec6e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/carthage-software/mago/zipball/4f64a85e4b4c5632eae895a8d8564898ffcaec6e", + "reference": "4f64a85e4b4c5632eae895a8d8564898ffcaec6e", + "shasum": "" + }, + "require": { + "php": "~8.1 || ~8.2 || ~8.3 || ~8.4 || ~8.5 || ~8.6", + "revolt/event-loop": "^1.0.9" + }, + "require-dev": { + "phpunit/phpunit": "^10.5", + "twig/twig": "^3.30" + }, + "suggest": { + "ext-curl": "To show binary download progress" + }, + "bin": [ + "composer/bin/mago" + ], + "type": "library", + "autoload": { + "files": [ + "composer/src/functions.php", + "composer/src/internal.php" + ], + "psr-4": { + "Mago\\": "composer/src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT OR Apache-2.0" + ], + "authors": [ + { + "name": "Seifeddine Gmati", + "email": "azjezz@carthage.software" + } + ], + "description": "Mago is a toolchain for PHP that aims to provide a set of tools to help developers write better code.", + "keywords": [ + "dev" + ], + "support": { + "issues": "https://github.com/carthage-software/mago/issues", + "source": "https://github.com/carthage-software/mago/tree/1.60.1" + }, + "funding": [ + { + "url": "https://github.com/azjezz", + "type": "github" + } + ], + "time": "2026-11-15T03:04:38+00:00" + }, + { + "name": "myclabs/deep-copy", + "version": "1.14.0", + "source": { + "type": "git", + "url": "https://github.com/myclabs/DeepCopy.git", + "reference": "8680aa248f8e07bc8fb43f56f0f5fc77a0c96aae" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/8680aa248f8e07bc8fb43f56f0f5fc77a0c96aae", + "reference": "8680aa248f8e07bc8fb43f56f0f5fc77a0c96aae", + "shasum": "" + }, + "require": { + "php": "^8.0" + }, + "conflict": { + "doctrine/collections": "<1.6.8", + "doctrine/common": "<2.13.3 || >=3 <3.2.2" + }, + "require-dev": { + "doctrine/collections": "^1.6.8", + "doctrine/common": "^2.13.3 || ^3.2.2", + "phpspec/prophecy": "^1.10", + "phpunit/phpunit": "^7.5.20 || ^8.5.23 || ^9.5.13" + }, + "type": "library", + "autoload": { + "files": [ + "src/DeepCopy/deep_copy.php" + ], + "psr-4": { + "DeepCopy\\": "src/DeepCopy/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Create deep copies (clones) of your objects", + "keywords": [ + "clone", + "copy", + "duplicate", + "object", + "object graph" + ], + "support": { + "issues": "https://github.com/myclabs/DeepCopy/issues", + "source": "https://github.com/myclabs/DeepCopy/tree/1.14.0" + }, + "funding": [ + { + "url": "https://github.com/mnapoli", + "type": "github" + } + ], + "time": "2026-08-11T10:17:44+00:00" + }, + { + "name": "nikic/php-parser", + "version": "v5.9.0", + "source": { + "type": "git", + "url": "https://github.com/nikic/PHP-Parser.git", + "reference": "9e33da9553fe7786f0962b35f4e4ecf01be89def" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/9e33da9553fe7786f0962b35f4e4ecf01be89def", + "reference": "9e33da9553fe7786f0962b35f4e4ecf01be89def", + "shasum": "" + }, + "require": { + "ext-json": "*", + "ext-tokenizer": "*", + "php": ">=7.4" + }, + "require-dev": { + "ircmaxell/php-yacc": "^0.0.7", + "phpunit/phpunit": "^9.0" + }, + "bin": [ + "bin/php-parse" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "5.x-dev" + } + }, + "autoload": { + "psr-4": { + "PhpParser\\": "lib/PhpParser" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Nikita Popov" + } + ], + "description": "A PHP parser written in PHP", + "keywords": [ + "parser", + "php" + ], + "support": { + "issues": "https://github.com/nikic/PHP-Parser/issues", + "source": "https://github.com/nikic/PHP-Parser/tree/v5.9.0" + }, + "time": "2026-09-13T18:51:52+00:00" + }, + { + "name": "phar-io/manifest", + "version": "2.0.4", + "source": { + "type": "git", + "url": "https://github.com/phar-io/manifest.git", + "reference": "54750ef60c58e43759730615a392c31c80e23176" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phar-io/manifest/zipball/54750ef60c58e43759730615a392c31c80e23176", + "reference": "54750ef60c58e43759730615a392c31c80e23176", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-libxml": "*", + "ext-phar": "*", + "ext-xmlwriter": "*", + "phar-io/version": "^3.0.1", + "php": "^7.2 || ^8.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Arne Blankerts", + "email": "arne@blankerts.de", + "role": "Developer" + }, + { + "name": "Sebastian Heuer", + "email": "sebastian@phpeople.de", + "role": "Developer" + }, + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "Developer" + } + ], + "description": "Component for reading phar.io manifest information from a PHP Archive (PHAR)", + "support": { + "issues": "https://github.com/phar-io/manifest/issues", + "source": "https://github.com/phar-io/manifest/tree/2.0.4" + }, + "funding": [ + { + "url": "https://github.com/theseer", + "type": "github" + } + ], + "time": "2024-03-03T12:33:53+00:00" + }, + { + "name": "phar-io/version", + "version": "3.2.1", + "source": { + "type": "git", + "url": "https://github.com/phar-io/version.git", + "reference": "4f7fd7836c6f332bb2933569e566a0d6c4cbed74" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phar-io/version/zipball/4f7fd7836c6f332bb2933569e566a0d6c4cbed74", + "reference": "4f7fd7836c6f332bb2933569e566a0d6c4cbed74", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "type": "library", + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Arne Blankerts", + "email": "arne@blankerts.de", + "role": "Developer" + }, + { + "name": "Sebastian Heuer", + "email": "sebastian@phpeople.de", + "role": "Developer" + }, + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "Developer" + } + ], + "description": "Library for handling version information and constraints", + "support": { + "issues": "https://github.com/phar-io/version/issues", + "source": "https://github.com/phar-io/version/tree/3.2.1" + }, + "time": "2022-02-21T01:04:05+00:00" + }, + { + "name": "phpstan/phpstan", + "version": "1.12.34", + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/4dd89ca7aa30fdc6760be21550d583bcc32e8476", + "reference": "4dd89ca7aa30fdc6760be21550d583bcc32e8476", + "shasum": "" + }, + "require": { + "php": "^7.2|^8.0" + }, + "conflict": { + "phpstan/phpstan-shim": "*" + }, + "bin": [ + "phpstan", + "phpstan.phar" + ], + "type": "library", + "autoload": { + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "PHPStan - PHP Static Analysis Tool", + "keywords": [ + "dev", + "static analysis" + ], + "support": { + "docs": "https://phpstan.org/user-guide/getting-started", + "forum": "https://github.com/phpstan/phpstan/discussions", + "issues": "https://github.com/phpstan/phpstan/issues", + "security": "https://github.com/phpstan/phpstan/security/policy", + "source": "https://github.com/phpstan/phpstan-src" + }, + "funding": [ + { + "url": "https://github.com/ondrejmirtes", + "type": "github" + }, + { + "url": "https://github.com/phpstan", + "type": "github" + } + ], + "time": "2026-07-28T10:04:39+00:00" + }, + { + "name": "phpunit/php-code-coverage", + "version": "11.0.12", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-code-coverage.git", + "reference": "2c1ed04922802c15e1de5d7447b4856de949cf56" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/2c1ed04922802c15e1de5d7447b4856de949cf56", + "reference": "2c1ed04922802c15e1de5d7447b4856de949cf56", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-libxml": "*", + "ext-xmlwriter": "*", + "nikic/php-parser": "^5.7.0", + "php": ">=8.2", + "phpunit/php-file-iterator": "^5.1.0", + "phpunit/php-text-template": "^4.0.1", + "sebastian/code-unit-reverse-lookup": "^4.0.1", + "sebastian/complexity": "^4.0.1", + "sebastian/environment": "^7.2.1", + "sebastian/lines-of-code": "^3.0.1", + "sebastian/version": "^5.0.2", + "theseer/tokenizer": "^1.3.1" + }, + "require-dev": { + "phpunit/phpunit": "^11.5.46" + }, + "suggest": { + "ext-pcov": "PHP extension that provides line coverage", + "ext-xdebug": "PHP extension that provides line coverage as well as branch and path coverage" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "11.0.x-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library that provides collection, processing, and rendering functionality for PHP code coverage information.", + "homepage": "https://github.com/sebastianbergmann/php-code-coverage", + "keywords": [ + "coverage", + "testing", + "xunit" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-code-coverage/issues", + "security": "https://github.com/sebastianbergmann/php-code-coverage/security/policy", + "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/11.0.12" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + }, + { + "url": "https://liberapay.com/sebastianbergmann", + "type": "liberapay" + }, + { + "url": "https://thanks.dev/u/gh/sebastianbergmann", + "type": "thanks_dev" + }, + { + "url": "https://tidelift.com/funding/github/packagist/phpunit/php-code-coverage", + "type": "tidelift" + } + ], + "time": "2025-12-24T07:01:01+00:00" + }, + { + "name": "phpunit/php-file-iterator", + "version": "5.1.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-file-iterator.git", + "reference": "2f3a64888c814fc235386b7387dd5b5ed92ad903" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/2f3a64888c814fc235386b7387dd5b5ed92ad903", + "reference": "2f3a64888c814fc235386b7387dd5b5ed92ad903", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "5.1-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "FilterIterator implementation that filters files based on a list of suffixes.", + "homepage": "https://github.com/sebastianbergmann/php-file-iterator/", + "keywords": [ + "filesystem", + "iterator" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-file-iterator/issues", + "security": "https://github.com/sebastianbergmann/php-file-iterator/security/policy", + "source": "https://github.com/sebastianbergmann/php-file-iterator/tree/5.1.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + }, + { + "url": "https://liberapay.com/sebastianbergmann", + "type": "liberapay" + }, + { + "url": "https://thanks.dev/u/gh/sebastianbergmann", + "type": "thanks_dev" + }, + { + "url": "https://tidelift.com/funding/github/packagist/phpunit/php-file-iterator", + "type": "tidelift" + } + ], + "time": "2026-02-02T13:52:54+00:00" + }, + { + "name": "phpunit/php-invoker", + "version": "5.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-invoker.git", + "reference": "c1ca3814734c07492b3d4c5f794f4b0995333da2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-invoker/zipball/c1ca3814734c07492b3d4c5f794f4b0995333da2", + "reference": "c1ca3814734c07492b3d4c5f794f4b0995333da2", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "ext-pcntl": "*", + "phpunit/phpunit": "^11.0" + }, + "suggest": { + "ext-pcntl": "*" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "5.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Invoke callables with a timeout", + "homepage": "https://github.com/sebastianbergmann/php-invoker/", + "keywords": [ + "process" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-invoker/issues", + "security": "https://github.com/sebastianbergmann/php-invoker/security/policy", + "source": "https://github.com/sebastianbergmann/php-invoker/tree/5.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T05:07:44+00:00" + }, + { + "name": "phpunit/php-text-template", + "version": "4.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-text-template.git", + "reference": "3e0404dc6b300e6bf56415467ebcb3fe4f33e964" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-text-template/zipball/3e0404dc6b300e6bf56415467ebcb3fe4f33e964", + "reference": "3e0404dc6b300e6bf56415467ebcb3fe4f33e964", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "4.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Simple template engine.", + "homepage": "https://github.com/sebastianbergmann/php-text-template/", + "keywords": [ + "template" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-text-template/issues", + "security": "https://github.com/sebastianbergmann/php-text-template/security/policy", + "source": "https://github.com/sebastianbergmann/php-text-template/tree/4.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T05:08:43+00:00" + }, + { + "name": "phpunit/php-timer", + "version": "7.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-timer.git", + "reference": "3b415def83fbcb41f991d9ebf16ae4ad8b7837b3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/3b415def83fbcb41f991d9ebf16ae4ad8b7837b3", + "reference": "3b415def83fbcb41f991d9ebf16ae4ad8b7837b3", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "7.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Utility class for timing", + "homepage": "https://github.com/sebastianbergmann/php-timer/", + "keywords": [ + "timer" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/php-timer/issues", + "security": "https://github.com/sebastianbergmann/php-timer/security/policy", + "source": "https://github.com/sebastianbergmann/php-timer/tree/7.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T05:09:35+00:00" + }, + { + "name": "phpunit/phpunit", + "version": "11.5.58", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/phpunit.git", + "reference": "c14b3145a2fcfa5dd9b25ee999ce2ba5933adf6f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/c14b3145a2fcfa5dd9b25ee999ce2ba5933adf6f", + "reference": "c14b3145a2fcfa5dd9b25ee999ce2ba5933adf6f", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-filter": "*", + "ext-json": "*", + "ext-libxml": "*", + "ext-mbstring": "*", + "ext-xmlwriter": "*", + "myclabs/deep-copy": "^1.14.0", + "phar-io/manifest": "^2.0.4", + "phar-io/version": "^3.2.1", + "php": ">=8.2", + "phpunit/php-code-coverage": "^11.0.12", + "phpunit/php-file-iterator": "^5.1.1", + "phpunit/php-invoker": "^5.0.1", + "phpunit/php-text-template": "^4.0.1", + "phpunit/php-timer": "^7.0.1", + "sebastian/cli-parser": "^3.0.2", + "sebastian/code-unit": "^3.0.3", + "sebastian/comparator": "^6.3.3", + "sebastian/diff": "^6.0.2", + "sebastian/environment": "^7.2.1", + "sebastian/exporter": "^6.3.2", + "sebastian/global-state": "^7.0.2", + "sebastian/object-enumerator": "^6.0.1", + "sebastian/recursion-context": "^6.0.3", + "sebastian/type": "^5.1.3", + "sebastian/version": "^5.0.2", + "staabm/side-effects-detector": "^1.0.5" + }, + "suggest": { + "ext-soap": "To be able to generate mocks based on WSDL files" + }, + "bin": [ + "phpunit" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "11.5-dev" + } + }, + "autoload": { + "files": [ + "src/Framework/Assert/Functions.php" + ], + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "The PHP Unit Testing framework.", + "homepage": "https://phpunit.de/", + "keywords": [ + "phpunit", + "testing", + "xunit" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/phpunit/issues", + "security": "https://github.com/sebastianbergmann/phpunit/security/policy", + "source": "https://github.com/sebastianbergmann/phpunit/tree/11.5.58" + }, + "funding": [ + { + "url": "https://phpunit.de/sponsoring.html", + "type": "other" + } + ], + "time": "2026-11-13T11:08:08+00:00" + }, + { + "name": "revolt/event-loop", + "version": "v1.0.9", + "source": { + "type": "git", + "url": "https://github.com/revoltphp/event-loop.git", + "reference": "44061cf513e53c6200372fc935ac42271566295d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/revoltphp/event-loop/zipball/44061cf513e53c6200372fc935ac42271566295d", + "reference": "44061cf513e53c6200372fc935ac42271566295d", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "require-dev": { + "ext-json": "*", + "jetbrains/phpstorm-stubs": "^2019.3", + "phpunit/phpunit": "^9", + "psalm/phar": "6.16.*" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.x-dev" + } + }, + "autoload": { + "psr-4": { + "Revolt\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Aaron Piotrowski", + "email": "aaron@trowski.com" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "ceesjank@gmail.com" + }, + { + "name": "Christian Lück", + "email": "christian@clue.engineering" + }, + { + "name": "Niklas Keller", + "email": "me@kelunik.com" + } + ], + "description": "Rock-solid event loop for concurrent PHP applications.", + "keywords": [ + "async", + "asynchronous", + "concurrency", + "event", + "event-loop", + "non-blocking", + "scheduler" + ], + "support": { + "issues": "https://github.com/revoltphp/event-loop/issues", + "source": "https://github.com/revoltphp/event-loop/tree/v1.0.9" + }, + "time": "2026-05-16T17:55:38+00:00" + }, + { + "name": "sebastian/cli-parser", + "version": "3.0.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/cli-parser.git", + "reference": "15c5dd40dc4f38794d383bb95465193f5e0ae180" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/cli-parser/zipball/15c5dd40dc4f38794d383bb95465193f5e0ae180", + "reference": "15c5dd40dc4f38794d383bb95465193f5e0ae180", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library for parsing CLI options", + "homepage": "https://github.com/sebastianbergmann/cli-parser", + "support": { + "issues": "https://github.com/sebastianbergmann/cli-parser/issues", + "security": "https://github.com/sebastianbergmann/cli-parser/security/policy", + "source": "https://github.com/sebastianbergmann/cli-parser/tree/3.0.2" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T04:41:36+00:00" + }, + { + "name": "sebastian/code-unit", + "version": "3.0.3", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/code-unit.git", + "reference": "54391c61e4af8078e5b276ab082b6d3c54c9ad64" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/code-unit/zipball/54391c61e4af8078e5b276ab082b6d3c54c9ad64", + "reference": "54391c61e4af8078e5b276ab082b6d3c54c9ad64", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Collection of value objects that represent the PHP code units", + "homepage": "https://github.com/sebastianbergmann/code-unit", + "support": { + "issues": "https://github.com/sebastianbergmann/code-unit/issues", + "security": "https://github.com/sebastianbergmann/code-unit/security/policy", + "source": "https://github.com/sebastianbergmann/code-unit/tree/3.0.3" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2025-03-19T07:56:08+00:00" + }, + { + "name": "sebastian/code-unit-reverse-lookup", + "version": "4.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/code-unit-reverse-lookup.git", + "reference": "183a9b2632194febd219bb9246eee421dad8d45e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/code-unit-reverse-lookup/zipball/183a9b2632194febd219bb9246eee421dad8d45e", + "reference": "183a9b2632194febd219bb9246eee421dad8d45e", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "4.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Looks up which function or method a line of code belongs to", + "homepage": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/", + "support": { + "issues": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/issues", + "security": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/security/policy", + "source": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/tree/4.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T04:45:54+00:00" + }, + { + "name": "sebastian/comparator", + "version": "6.3.3", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/comparator.git", + "reference": "2c95e1e86cb8dd41beb8d502057d1081ccc8eca9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/2c95e1e86cb8dd41beb8d502057d1081ccc8eca9", + "reference": "2c95e1e86cb8dd41beb8d502057d1081ccc8eca9", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-mbstring": "*", + "php": ">=8.2", + "sebastian/diff": "^6.0", + "sebastian/exporter": "^6.0" + }, + "require-dev": { + "phpunit/phpunit": "^11.4" + }, + "suggest": { + "ext-bcmath": "For comparing BcMath\\Number objects" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "6.3-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Jeff Welch", + "email": "whatthejeff@gmail.com" + }, + { + "name": "Volker Dusch", + "email": "github@wallbash.com" + }, + { + "name": "Bernhard Schussek", + "email": "bschussek@2bepublished.at" + } + ], + "description": "Provides the functionality to compare PHP values for equality", + "homepage": "https://github.com/sebastianbergmann/comparator", + "keywords": [ + "comparator", + "compare", + "equality" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/comparator/issues", + "security": "https://github.com/sebastianbergmann/comparator/security/policy", + "source": "https://github.com/sebastianbergmann/comparator/tree/6.3.3" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + }, + { + "url": "https://liberapay.com/sebastianbergmann", + "type": "liberapay" + }, + { + "url": "https://thanks.dev/u/gh/sebastianbergmann", + "type": "thanks_dev" + }, + { + "url": "https://tidelift.com/funding/github/packagist/sebastian/comparator", + "type": "tidelift" + } + ], + "time": "2026-01-24T09:26:40+00:00" + }, + { + "name": "sebastian/complexity", + "version": "4.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/complexity.git", + "reference": "ee41d384ab1906c68852636b6de493846e13e5a0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/complexity/zipball/ee41d384ab1906c68852636b6de493846e13e5a0", + "reference": "ee41d384ab1906c68852636b6de493846e13e5a0", + "shasum": "" + }, + "require": { + "nikic/php-parser": "^5.0", + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "4.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library for calculating the complexity of PHP code units", + "homepage": "https://github.com/sebastianbergmann/complexity", + "support": { + "issues": "https://github.com/sebastianbergmann/complexity/issues", + "security": "https://github.com/sebastianbergmann/complexity/security/policy", + "source": "https://github.com/sebastianbergmann/complexity/tree/4.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T04:49:50+00:00" + }, + { + "name": "sebastian/diff", + "version": "6.0.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/diff.git", + "reference": "b4ccd857127db5d41a5b676f24b51371d76d8544" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/b4ccd857127db5d41a5b676f24b51371d76d8544", + "reference": "b4ccd857127db5d41a5b676f24b51371d76d8544", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0", + "symfony/process": "^4.2 || ^5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "6.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Kore Nordmann", + "email": "mail@kore-nordmann.de" + } + ], + "description": "Diff implementation", + "homepage": "https://github.com/sebastianbergmann/diff", + "keywords": [ + "diff", + "udiff", + "unidiff", + "unified diff" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/diff/issues", + "security": "https://github.com/sebastianbergmann/diff/security/policy", + "source": "https://github.com/sebastianbergmann/diff/tree/6.0.2" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T04:53:05+00:00" + }, + { + "name": "sebastian/environment", + "version": "7.2.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/environment.git", + "reference": "a5c75038693ad2e8d4b6c15ba2403532647830c4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/a5c75038693ad2e8d4b6c15ba2403532647830c4", + "reference": "a5c75038693ad2e8d4b6c15ba2403532647830c4", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.3" + }, + "suggest": { + "ext-posix": "*" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "7.2-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Provides functionality to handle HHVM/PHP environments", + "homepage": "https://github.com/sebastianbergmann/environment", + "keywords": [ + "Xdebug", + "environment", + "hhvm" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/environment/issues", + "security": "https://github.com/sebastianbergmann/environment/security/policy", + "source": "https://github.com/sebastianbergmann/environment/tree/7.2.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + }, + { + "url": "https://liberapay.com/sebastianbergmann", + "type": "liberapay" + }, + { + "url": "https://thanks.dev/u/gh/sebastianbergmann", + "type": "thanks_dev" + }, + { + "url": "https://tidelift.com/funding/github/packagist/sebastian/environment", + "type": "tidelift" + } + ], + "time": "2025-05-21T11:55:47+00:00" + }, + { + "name": "sebastian/exporter", + "version": "6.3.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/exporter.git", + "reference": "70a298763b40b213ec087c51c739efcaa90bcd74" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/70a298763b40b213ec087c51c739efcaa90bcd74", + "reference": "70a298763b40b213ec087c51c739efcaa90bcd74", + "shasum": "" + }, + "require": { + "ext-mbstring": "*", + "php": ">=8.2", + "sebastian/recursion-context": "^6.0" + }, + "require-dev": { + "phpunit/phpunit": "^11.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "6.3-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Jeff Welch", + "email": "whatthejeff@gmail.com" + }, + { + "name": "Volker Dusch", + "email": "github@wallbash.com" + }, + { + "name": "Adam Harvey", + "email": "aharvey@php.net" + }, + { + "name": "Bernhard Schussek", + "email": "bschussek@gmail.com" + } + ], + "description": "Provides the functionality to export PHP variables for visualization", + "homepage": "https://www.github.com/sebastianbergmann/exporter", + "keywords": [ + "export", + "exporter" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/exporter/issues", + "security": "https://github.com/sebastianbergmann/exporter/security/policy", + "source": "https://github.com/sebastianbergmann/exporter/tree/6.3.2" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + }, + { + "url": "https://liberapay.com/sebastianbergmann", + "type": "liberapay" + }, + { + "url": "https://thanks.dev/u/gh/sebastianbergmann", + "type": "thanks_dev" + }, + { + "url": "https://tidelift.com/funding/github/packagist/sebastian/exporter", + "type": "tidelift" + } + ], + "time": "2025-09-24T06:12:51+00:00" + }, + { + "name": "sebastian/global-state", + "version": "7.0.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/global-state.git", + "reference": "3be331570a721f9a4b5917f4209773de17f747d7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/global-state/zipball/3be331570a721f9a4b5917f4209773de17f747d7", + "reference": "3be331570a721f9a4b5917f4209773de17f747d7", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "sebastian/object-reflector": "^4.0", + "sebastian/recursion-context": "^6.0" + }, + "require-dev": { + "ext-dom": "*", + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "7.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Snapshotting of global state", + "homepage": "https://www.github.com/sebastianbergmann/global-state", + "keywords": [ + "global state" + ], + "support": { + "issues": "https://github.com/sebastianbergmann/global-state/issues", + "security": "https://github.com/sebastianbergmann/global-state/security/policy", + "source": "https://github.com/sebastianbergmann/global-state/tree/7.0.2" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T04:57:36+00:00" + }, + { + "name": "sebastian/lines-of-code", + "version": "3.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/lines-of-code.git", + "reference": "d36ad0d782e5756913e42ad87cb2890f4ffe467a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/lines-of-code/zipball/d36ad0d782e5756913e42ad87cb2890f4ffe467a", + "reference": "d36ad0d782e5756913e42ad87cb2890f4ffe467a", + "shasum": "" + }, + "require": { + "nikic/php-parser": "^5.0", + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library for counting the lines of code in PHP source code", + "homepage": "https://github.com/sebastianbergmann/lines-of-code", + "support": { + "issues": "https://github.com/sebastianbergmann/lines-of-code/issues", + "security": "https://github.com/sebastianbergmann/lines-of-code/security/policy", + "source": "https://github.com/sebastianbergmann/lines-of-code/tree/3.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T04:58:38+00:00" + }, + { + "name": "sebastian/object-enumerator", + "version": "6.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/object-enumerator.git", + "reference": "f5b498e631a74204185071eb41f33f38d64608aa" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/object-enumerator/zipball/f5b498e631a74204185071eb41f33f38d64608aa", + "reference": "f5b498e631a74204185071eb41f33f38d64608aa", + "shasum": "" + }, + "require": { + "php": ">=8.2", + "sebastian/object-reflector": "^4.0", + "sebastian/recursion-context": "^6.0" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "6.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Traverses array structures and object graphs to enumerate all referenced objects", + "homepage": "https://github.com/sebastianbergmann/object-enumerator/", + "support": { + "issues": "https://github.com/sebastianbergmann/object-enumerator/issues", + "security": "https://github.com/sebastianbergmann/object-enumerator/security/policy", + "source": "https://github.com/sebastianbergmann/object-enumerator/tree/6.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T05:00:13+00:00" + }, + { + "name": "sebastian/object-reflector", + "version": "4.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/object-reflector.git", + "reference": "6e1a43b411b2ad34146dee7524cb13a068bb35f9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/object-reflector/zipball/6e1a43b411b2ad34146dee7524cb13a068bb35f9", + "reference": "6e1a43b411b2ad34146dee7524cb13a068bb35f9", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "4.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + } + ], + "description": "Allows reflection of object attributes, including inherited and non-public ones", + "homepage": "https://github.com/sebastianbergmann/object-reflector/", + "support": { + "issues": "https://github.com/sebastianbergmann/object-reflector/issues", + "security": "https://github.com/sebastianbergmann/object-reflector/security/policy", + "source": "https://github.com/sebastianbergmann/object-reflector/tree/4.0.1" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-07-03T05:01:32+00:00" + }, + { + "name": "sebastian/recursion-context", + "version": "6.0.3", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/recursion-context.git", + "reference": "f6458abbf32a6c8174f8f26261475dc133b3d9dc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/recursion-context/zipball/f6458abbf32a6c8174f8f26261475dc133b3d9dc", + "reference": "f6458abbf32a6c8174f8f26261475dc133b3d9dc", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "6.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Jeff Welch", + "email": "whatthejeff@gmail.com" + }, + { + "name": "Adam Harvey", + "email": "aharvey@php.net" + } + ], + "description": "Provides functionality to recursively process PHP variables", + "homepage": "https://github.com/sebastianbergmann/recursion-context", + "support": { + "issues": "https://github.com/sebastianbergmann/recursion-context/issues", + "security": "https://github.com/sebastianbergmann/recursion-context/security/policy", + "source": "https://github.com/sebastianbergmann/recursion-context/tree/6.0.3" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + }, + { + "url": "https://liberapay.com/sebastianbergmann", + "type": "liberapay" + }, + { + "url": "https://thanks.dev/u/gh/sebastianbergmann", + "type": "thanks_dev" + }, + { + "url": "https://tidelift.com/funding/github/packagist/sebastian/recursion-context", + "type": "tidelift" + } + ], + "time": "2025-08-13T04:42:22+00:00" + }, + { + "name": "sebastian/type", + "version": "5.1.3", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/type.git", + "reference": "f77d2d4e78738c98d9a68d2596fe5e8fa380f449" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/type/zipball/f77d2d4e78738c98d9a68d2596fe5e8fa380f449", + "reference": "f77d2d4e78738c98d9a68d2596fe5e8fa380f449", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "require-dev": { + "phpunit/phpunit": "^11.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "5.1-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Collection of value objects that represent the types of the PHP type system", + "homepage": "https://github.com/sebastianbergmann/type", + "support": { + "issues": "https://github.com/sebastianbergmann/type/issues", + "security": "https://github.com/sebastianbergmann/type/security/policy", + "source": "https://github.com/sebastianbergmann/type/tree/5.1.3" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + }, + { + "url": "https://liberapay.com/sebastianbergmann", + "type": "liberapay" + }, + { + "url": "https://thanks.dev/u/gh/sebastianbergmann", + "type": "thanks_dev" + }, + { + "url": "https://tidelift.com/funding/github/packagist/sebastian/type", + "type": "tidelift" + } + ], + "time": "2025-08-09T06:55:48+00:00" + }, + { + "name": "sebastian/version", + "version": "5.0.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/version.git", + "reference": "c687e3387b99f5b03b6caa64c74b63e2936ff874" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/version/zipball/c687e3387b99f5b03b6caa64c74b63e2936ff874", + "reference": "c687e3387b99f5b03b6caa64c74b63e2936ff874", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "5.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library that helps with managing the version number of Git-hosted PHP projects", + "homepage": "https://github.com/sebastianbergmann/version", + "support": { + "issues": "https://github.com/sebastianbergmann/version/issues", + "security": "https://github.com/sebastianbergmann/version/security/policy", + "source": "https://github.com/sebastianbergmann/version/tree/5.0.2" + }, + "funding": [ + { + "url": "https://github.com/sebastianbergmann", + "type": "github" + } + ], + "time": "2024-10-09T05:16:32+00:00" + }, + { + "name": "staabm/side-effects-detector", + "version": "1.0.5", + "source": { + "type": "git", + "url": "https://github.com/staabm/side-effects-detector.git", + "reference": "d8334211a140ce329c13726d4a715adbddd0a163" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/staabm/side-effects-detector/zipball/d8334211a140ce329c13726d4a715adbddd0a163", + "reference": "d8334211a140ce329c13726d4a715adbddd0a163", + "shasum": "" + }, + "require": { + "ext-tokenizer": "*", + "php": "^7.4 || ^8.0" + }, + "require-dev": { + "phpstan/extension-installer": "^1.4.3", + "phpstan/phpstan": "^1.12.6", + "phpunit/phpunit": "^9.6.21", + "symfony/var-dumper": "^5.4.43", + "tomasvotruba/type-coverage": "1.0.0", + "tomasvotruba/unused-public": "1.0.0" + }, + "type": "library", + "autoload": { + "classmap": [ + "lib/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "A static analysis tool to detect side effects in PHP code", + "keywords": [ + "static analysis" + ], + "support": { + "issues": "https://github.com/staabm/side-effects-detector/issues", + "source": "https://github.com/staabm/side-effects-detector/tree/1.0.5" + }, + "funding": [ + { + "url": "https://github.com/staabm", + "type": "github" + } + ], + "time": "2024-10-20T05:08:20+00:00" + }, + { + "name": "theseer/tokenizer", + "version": "1.3.1", + "source": { + "type": "git", + "url": "https://github.com/theseer/tokenizer.git", + "reference": "b7489ce515e168639d17feec34b8847c326b0b3c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/theseer/tokenizer/zipball/b7489ce515e168639d17feec34b8847c326b0b3c", + "reference": "b7489ce515e168639d17feec34b8847c326b0b3c", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "ext-tokenizer": "*", + "ext-xmlwriter": "*", + "php": "^7.2 || ^8.0" + }, + "type": "library", + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Arne Blankerts", + "email": "arne@blankerts.de", + "role": "Developer" + } + ], + "description": "A small library for converting tokenized PHP source code into XML and potentially other formats", + "support": { + "issues": "https://github.com/theseer/tokenizer/issues", + "source": "https://github.com/theseer/tokenizer/tree/1.3.1" + }, + "funding": [ + { + "url": "https://github.com/theseer", + "type": "github" + } + ], + "time": "2025-11-17T20:03:58+00:00" + } + ], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": {}, + "prefer-stable": true, + "prefer-lowest": false, + "platform": { + "php": ">=8.3", + "ext-json": "*" + }, + "platform-dev": {}, + "plugin-api-version": "2.9.0" +} diff --git a/docs/ARQUITECTURA.md b/docs/ARQUITECTURA.md new file mode 100644 index 0000000..6d34c1c --- /dev/null +++ b/docs/ARQUITECTURA.md @@ -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. diff --git a/docs/EJEMPLOS.md b/docs/EJEMPLOS.md new file mode 100644 index 0000000..1c48613 --- /dev/null +++ b/docs/EJEMPLOS.md @@ -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 +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_` 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 + $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 */ + protected function toArray(Model $model): array + { + return $model->toArray(); + } + + /** + * Traduce `sort`/`order` del query string al formato del ORM. + * + * @param array $query + * @return list + */ + 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 +error(new Conflict('An articulo with that code already exists.')); + } + } +} +``` + +--- + +## 5. Test de la API completa + +```php +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> */ + 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. diff --git a/docs/GUIA-PROGRAMADOR.md b/docs/GUIA-PROGRAMADOR.md new file mode 100644 index 0000000..9f1f89d --- /dev/null +++ b/docs/GUIA-PROGRAMADOR.md @@ -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 +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 +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 +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 + 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` | | + +### `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` | | +| `dispatch(Request): Response` | nunca lanza | + +### `Route` + +`method()`, `pattern()`, `handler()`, `parameters(): list`, +`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)`, `with(Middleware): self`, `middlewares()`, `isEmpty()`, +`process(Request, callable): Response`. + +### Middlewares + +| Clase | Constructor | +|---|---| +| `Security\BearerAuth` | `(callable $resolver)` | +| `Security\RequireRole` | `(list $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. diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..a2a2da8 --- /dev/null +++ b/docs/README.md @@ -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 +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. diff --git a/docs/especificaciones-controllers.md b/docs/especificaciones-controllers.md new file mode 100644 index 0000000..f08ef0b --- /dev/null +++ b/docs/especificaciones-controllers.md @@ -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> */ + public function findAll(array $query = []): array; + + /** @return array */ + public function find(int|string $id): ?array; + + /** @return array */ + public function create(array $values): array; + + /** @return array */ + 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>` 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 ` (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. diff --git a/mago.toml b/mago.toml new file mode 100644 index 0000000..52f3b21 --- /dev/null +++ b/mago.toml @@ -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 diff --git a/phpstan.neon b/phpstan.neon new file mode 100644 index 0000000..a0a7c20 --- /dev/null +++ b/phpstan.neon @@ -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 diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..f62925e --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,20 @@ + + + + + tests/Unit + + + + + src + + + diff --git a/src/Controller.php b/src/Controller.php new file mode 100644 index 0000000..62e7de2 --- /dev/null +++ b/src/Controller.php @@ -0,0 +1,81 @@ + $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> $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)); + } +} diff --git a/src/CrudController.php b/src/CrudController.php new file mode 100644 index 0000000..58cb0d5 --- /dev/null +++ b/src/CrudController.php @@ -0,0 +1,205 @@ +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 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 + */ + 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 */ + private const FILTER_KEYS = ['sort', 'order', 'q']; +} diff --git a/src/Exception/BadRequest.php b/src/Exception/BadRequest.php new file mode 100644 index 0000000..15fcbb5 --- /dev/null +++ b/src/Exception/BadRequest.php @@ -0,0 +1,26 @@ + */ + public function headers(): array + { + return []; + } + + /** @return array */ + public function toArray(): array + { + return ['code' => $this->errorCode(), 'message' => $this->getMessage()]; + } +} diff --git a/src/Exception/MethodNotAllowed.php b/src/Exception/MethodNotAllowed.php new file mode 100644 index 0000000..e8613f0 --- /dev/null +++ b/src/Exception/MethodNotAllowed.php @@ -0,0 +1,43 @@ + $allowed */ + public function __construct( + private readonly array $allowed, + ) { + parent::__construct(sprintf('Method not allowed. Accepted methods: %s.', implode( + ', ', + $allowed, + ))); + } + + /** @return list */ + public function allowed(): array + { + return $this->allowed; + } + + public function status(): int + { + return 405; + } + + public function errorCode(): string + { + return 'method_not_allowed'; + } + + /** @return array */ + public function headers(): array + { + return ['Allow' => implode(', ', $this->allowed)]; + } +} diff --git a/src/Exception/NotFound.php b/src/Exception/NotFound.php new file mode 100644 index 0000000..84524c8 --- /dev/null +++ b/src/Exception/NotFound.php @@ -0,0 +1,36 @@ + */ + public function headers(): array + { + return ['WWW-Authenticate' => 'Bearer']; + } +} diff --git a/src/Exception/ValidationFailed.php b/src/Exception/ValidationFailed.php new file mode 100644 index 0000000..8f60817 --- /dev/null +++ b/src/Exception/ValidationFailed.php @@ -0,0 +1,44 @@ +> $errors */ + public function __construct( + private readonly array $errors, + string $message = 'The submitted data is invalid.', + ) { + parent::__construct($message); + } + + /** @return array> */ + public function errors(): array + { + return $this->errors; + } + + public function status(): int + { + return 422; + } + + public function errorCode(): string + { + return 'validation_failed'; + } + + /** @return array */ + public function toArray(): array + { + return parent::toArray() + ['errors' => $this->errors]; + } +} diff --git a/src/JsonRequest.php b/src/JsonRequest.php new file mode 100644 index 0000000..cf1f35b --- /dev/null +++ b/src/JsonRequest.php @@ -0,0 +1,76 @@ + $query + * @param array $body + * @param array $headers + * @param array $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 */ + 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, + ); + } +} diff --git a/src/Middleware.php b/src/Middleware.php new file mode 100644 index 0000000..3d30cfc --- /dev/null +++ b/src/Middleware.php @@ -0,0 +1,22 @@ + $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; + } +} diff --git a/src/Middleware/Logging.php b/src/Middleware/Logging.php new file mode 100644 index 0000000..9fb314e --- /dev/null +++ b/src/Middleware/Logging.php @@ -0,0 +1,93 @@ +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): void */ + private mixed $sink; + + /** @var (callable(): float)|null */ + private mixed $clock; + + /** + * @param callable(string, string, array): 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; + } +} diff --git a/src/Pipeline.php b/src/Pipeline.php new file mode 100644 index 0000000..4c2770e --- /dev/null +++ b/src/Pipeline.php @@ -0,0 +1,58 @@ + */ + private array $middlewares; + + /** @param list $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 */ + 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); + } +} diff --git a/src/Request.php b/src/Request.php new file mode 100644 index 0000000..3180a23 --- /dev/null +++ b/src/Request.php @@ -0,0 +1,39 @@ + + */ + 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; +} diff --git a/src/ResourceGateway.php b/src/ResourceGateway.php new file mode 100644 index 0000000..20c496d --- /dev/null +++ b/src/ResourceGateway.php @@ -0,0 +1,46 @@ + $query + * @return list> + */ + public function findAll(array $query = []): array; + + /** @return array|null */ + public function find(int|string $id): ?array; + + /** + * @param array $values + * @return array + */ + public function create(array $values): array; + + /** + * @param array $values + * @return array|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 $query + */ + public function count(array $query = []): ?int; +} diff --git a/src/Response.php b/src/Response.php new file mode 100644 index 0000000..4908cf9 --- /dev/null +++ b/src/Response.php @@ -0,0 +1,74 @@ + $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 */ + 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, + ); + } +} diff --git a/src/Route.php b/src/Route.php new file mode 100644 index 0000000..e1b5655 --- /dev/null +++ b/src/Route.php @@ -0,0 +1,106 @@ + 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 */ + public function parameters(): array + { + return $this->parameters; + } + + /** + * Matches a path and returns the captured parameters, or `null` when it does not match. + * + * @return array|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[^/]+)$#`. + * + * 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} + */ + 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]; + } +} diff --git a/src/Router.php b/src/Router.php new file mode 100644 index 0000000..ce1b459 --- /dev/null +++ b/src/Router.php @@ -0,0 +1,162 @@ + */ + 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 */ + 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 $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()); + } + } +} diff --git a/src/Security/BearerAuth.php b/src/Security/BearerAuth.php new file mode 100644 index 0000000..2644055 --- /dev/null +++ b/src/Security/BearerAuth.php @@ -0,0 +1,68 @@ +` 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|null) */ + private mixed $resolver; + + /** + * @param callable(string): (array|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()); + } +} diff --git a/src/Security/Cors.php b/src/Security/Cors.php new file mode 100644 index 0000000..92ad56a --- /dev/null +++ b/src/Security/Cors.php @@ -0,0 +1,85 @@ + $allowedOrigins Exact origins, or `['*']`. + * @param list $allowedMethods + * @param list $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 */ + 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; + } +} diff --git a/src/Security/RateLimit.php b/src/Security/RateLimit.php new file mode 100644 index 0000000..cccb213 --- /dev/null +++ b/src/Security/RateLimit.php @@ -0,0 +1,115 @@ + */ + 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)(); + } +} diff --git a/src/Security/RequireRole.php b/src/Security/RequireRole.php new file mode 100644 index 0000000..a2f1703 --- /dev/null +++ b/src/Security/RequireRole.php @@ -0,0 +1,84 @@ + $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 $identity + * @return list + */ + 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()); + } +} diff --git a/tests/Fixture/ArrayGateway.php b/tests/Fixture/ArrayGateway.php new file mode 100644 index 0000000..43237b3 --- /dev/null +++ b/tests/Fixture/ArrayGateway.php @@ -0,0 +1,68 @@ +> $records */ + public function __construct( + private array $records = [], + ) {} + + /** @return list> */ + public function findAll(array $query = []): array + { + return array_values($this->records); + } + + /** @return array|null */ + public function find(int|string $id): ?array + { + return $this->records[$id] ?? null; + } + + /** @return array */ + public function create(array $values): array + { + $id = count($this->records) + 1; + $record = ['id' => $id] + $values; + $this->records[$id] = $record; + + return $record; + } + + /** @return array|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); + } +} diff --git a/tests/Unit/CrudControllerTest.php b/tests/Unit/CrudControllerTest.php new file mode 100644 index 0000000..ba01236 --- /dev/null +++ b/tests/Unit/CrudControllerTest.php @@ -0,0 +1,181 @@ +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 $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)); + } +} diff --git a/tests/Unit/JsonRequestTest.php b/tests/Unit/JsonRequestTest.php new file mode 100644 index 0000000..f6280d1 --- /dev/null +++ b/tests/Unit/JsonRequestTest.php @@ -0,0 +1,62 @@ + '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')); + } +} diff --git a/tests/Unit/Middleware/ContentNegotiationTest.php b/tests/Unit/Middleware/ContentNegotiationTest.php new file mode 100644 index 0000000..7b2a24d --- /dev/null +++ b/tests/Unit/Middleware/ContentNegotiationTest.php @@ -0,0 +1,113 @@ + 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')); + } +} diff --git a/tests/Unit/Middleware/LoggingTest.php b/tests/Unit/Middleware/LoggingTest.php new file mode 100644 index 0000000..7e999c7 --- /dev/null +++ b/tests/Unit/Middleware/LoggingTest.php @@ -0,0 +1,116 @@ +}> */ + 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); + } +} diff --git a/tests/Unit/PipelineTest.php b/tests/Unit/PipelineTest.php new file mode 100644 index 0000000..33a142f --- /dev/null +++ b/tests/Unit/PipelineTest.php @@ -0,0 +1,99 @@ +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 $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; + } +} diff --git a/tests/Unit/ResponseTest.php b/tests/Unit/ResponseTest.php new file mode 100644 index 0000000..0217668 --- /dev/null +++ b/tests/Unit/ResponseTest.php @@ -0,0 +1,78 @@ + 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']); + } +} diff --git a/tests/Unit/RouteTest.php b/tests/Unit/RouteTest.php new file mode 100644 index 0000000..cd0ac28 --- /dev/null +++ b/tests/Unit/RouteTest.php @@ -0,0 +1,71 @@ +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(); + } +} diff --git a/tests/Unit/RouterTest.php b/tests/Unit/RouterTest.php new file mode 100644 index 0000000..4f8ec43 --- /dev/null +++ b/tests/Unit/RouterTest.php @@ -0,0 +1,114 @@ +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); + } +} diff --git a/tests/Unit/Security/BearerAuthTest.php b/tests/Unit/Security/BearerAuthTest.php new file mode 100644 index 0000000..e96a9fc --- /dev/null +++ b/tests/Unit/Security/BearerAuthTest.php @@ -0,0 +1,128 @@ + 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([]); + } +} diff --git a/tests/Unit/Security/CorsTest.php b/tests/Unit/Security/CorsTest.php new file mode 100644 index 0000000..c4f6029 --- /dev/null +++ b/tests/Unit/Security/CorsTest.php @@ -0,0 +1,97 @@ + 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')); + } +} diff --git a/tests/Unit/Security/RateLimitTest.php b/tests/Unit/Security/RateLimitTest.php new file mode 100644 index 0000000..f038d9b --- /dev/null +++ b/tests/Unit/Security/RateLimitTest.php @@ -0,0 +1,113 @@ + 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)); + } +} diff --git a/tests/Unit/Security/RequireRoleTest.php b/tests/Unit/Security/RequireRoleTest.php new file mode 100644 index 0000000..ef0aac5 --- /dev/null +++ b/tests/Unit/Security/RequireRoleTest.php @@ -0,0 +1,103 @@ + 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()); + } +}