Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
93bc5d313f | ||
|
|
f83d36e64f | ||
|
|
afcb2e8449 | ||
|
|
4159e046c2 | ||
|
|
abdcc8b04e | ||
|
|
fb6ac985fe | ||
|
|
93914a2b38 | ||
|
|
807992ecab | ||
|
|
a20762a715 | ||
|
|
c586c2c16a |
No files matched your search
+7
-2
@@ -1,11 +1,16 @@
|
|||||||
* text=auto eol=lf
|
* text=auto eol=lf
|
||||||
|
|
||||||
# Files excluded from the distribution archive installed by Composer.
|
# Files excluded from the distribution archive installed by Composer.
|
||||||
/tests export-ignore
|
# export-ignore is not recursive: a directory entry does not cover its children.
|
||||||
|
/tests/** export-ignore
|
||||||
/.gitattributes export-ignore
|
/.gitattributes export-ignore
|
||||||
/.gitignore export-ignore
|
/.gitignore export-ignore
|
||||||
/.github export-ignore
|
|
||||||
/AGENTS.md export-ignore
|
/AGENTS.md export-ignore
|
||||||
/mago.toml export-ignore
|
/mago.toml export-ignore
|
||||||
/phpstan.neon export-ignore
|
/phpstan.neon export-ignore
|
||||||
/phpunit.xml.dist export-ignore
|
/phpunit.xml.dist export-ignore
|
||||||
|
/phpunit.coverage.xml.dist export-ignore
|
||||||
|
/node_modules/ export-ignore
|
||||||
|
/package.json export-ignore
|
||||||
|
/package-lock.json export-ignore
|
||||||
|
/.husky/** export-ignore
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
name: Tests
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [main]
|
|
||||||
pull_request:
|
|
||||||
branches: [main]
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
check:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
php: ['8.3', '8.4']
|
|
||||||
|
|
||||||
name: PHP ${{ matrix.php }}
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Set up PHP
|
|
||||||
uses: shivammathur/setup-php@v2
|
|
||||||
with:
|
|
||||||
php-version: ${{ matrix.php }}
|
|
||||||
extensions: json
|
|
||||||
coverage: none
|
|
||||||
tools: composer:v2
|
|
||||||
|
|
||||||
- name: Install dependencies
|
|
||||||
run: composer update --prefer-dist --no-interaction --no-progress
|
|
||||||
|
|
||||||
- name: Run gate
|
|
||||||
run: composer check
|
|
||||||
@@ -3,3 +3,4 @@
|
|||||||
.phpunit.result.cache
|
.phpunit.result.cache
|
||||||
.mago.cache
|
.mago.cache
|
||||||
coverage/
|
coverage/
|
||||||
|
node_modules/
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
composer check
|
||||||
@@ -37,8 +37,8 @@ salvo lo que difiere abajo. Léelos antes de tocar el toolchain.
|
|||||||
|
|
||||||
| | aquí | en `../orm` |
|
| | aquí | en `../orm` |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| PHP declarado | `>=8.3` | `>=8.3` (su prosa dice 8.2: gana el composer.json) |
|
| PHP declarado | `>=8.4` | `>=8.4` |
|
||||||
| Parser Mago / PHPStan | 8.2 / `80300` | 8.2 / `80200` |
|
| Parser Mago / PHPStan | 8.4 / `80400` | 8.4 / `80400` |
|
||||||
| `mago-baseline.toml` | **no existe**, y no debe crearse | existe |
|
| `mago-baseline.toml` | **no existe**, y no debe crearse | existe |
|
||||||
|
|
||||||
## Independencia del ORM (decisión de diseño, no descuido)
|
## Independencia del ORM (decisión de diseño, no descuido)
|
||||||
@@ -65,8 +65,8 @@ la app conecta el ORM por composición. Consecuencias que un agente rompería po
|
|||||||
|
|
||||||
## Entorno local
|
## Entorno local
|
||||||
|
|
||||||
- PHP: `C:\php8.4\php.exe` (8.4.19), Composer 2.10.3. La librería declara `>=8.3`, así que **no**
|
- PHP: `C:\php8.4\php.exe` (8.4.19), Composer 2.10.3. La librería declara `>=8.4`, así que toda la
|
||||||
uses sintaxis exclusiva de 8.4; por eso `(new Foo())->bar()` conserva los paréntesis.
|
sintaxis de 8.4 está disponible.
|
||||||
- `declare(strict_types=1)` en todo archivo, incluidos los tests.
|
- `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,
|
- 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í.
|
ni red. Un test que necesite un socket real está mal ubicado aquí.
|
||||||
@@ -87,9 +87,10 @@ vendor/bin/phpunit --configuration phpunit.xml.dist --filter NombreDelTest
|
|||||||
|
|
||||||
## Trampas del toolchain
|
## Trampas del toolchain
|
||||||
|
|
||||||
- **`php-version = "8.2"` en `mago.toml` es obligatorio.** Subirlo a 8.4 hace que `mago fmt`
|
- **`php-version = "8.4"` en `mago.toml` debe coincidir con el mínimo declarado.** El paquete
|
||||||
reescriba `(new X())->m()` como `new X()->m()`, que rompe el soporte declarado y ni siquiera parsea
|
promete `>=8.4`, así que `mago fmt` puede emitir `new X()->m()`. Si el soporte mínimo bajara,
|
||||||
cuando el resultado se asigna.
|
`php-version` tendría que bajar con él: con 8.4 el formatter elimina los paréntesis de
|
||||||
|
`(new X())->m()`, sintaxis que no parsea en 8.3 ni inferiores.
|
||||||
- `mago analyze` excluye `tests/` (no carga el autoloader de Composer): reportaría `TestCase` como
|
- `mago analyze` excluye `tests/` (no carga el autoloader de Composer): reportaría `TestCase` como
|
||||||
clase inexistente. PHPStan sí cubre los tests.
|
clase inexistente. PHPStan sí cubre los tests.
|
||||||
- **Sin baseline.** El baseline del ORM acepta `mixed` inherente a PDO. Aquí no hay PDO como
|
- **Sin baseline.** El baseline del ORM acepta `mixed` inherente a PDO. Aquí no hay PDO como
|
||||||
|
|||||||
@@ -3,13 +3,12 @@
|
|||||||
[](https://packagist.org/packages/camelia/controllers)
|
[](https://packagist.org/packages/camelia/controllers)
|
||||||
[](https://packagist.org/packages/camelia/controllers)
|
[](https://packagist.org/packages/camelia/controllers)
|
||||||
[](https://packagist.org/packages/camelia/controllers)
|
[](https://packagist.org/packages/camelia/controllers)
|
||||||
[](https://git.dr2gsistemas.duckdns.org/dr2gsistemas/camelia-controller/actions)
|
|
||||||
|
|
||||||
Framework-agnostic REST controller toolkit: routing, request parsing, validation and JSON responses
|
Framework-agnostic REST controller toolkit: routing, request parsing, validation and JSON responses
|
||||||
over any data source. Vanilla PHP, no framework.
|
over any data source. Vanilla PHP, no framework.
|
||||||
|
|
||||||
- **Package:** `camelia/controllers` — **Namespace:** `Camelia\Controllers`
|
- **Package:** `camelia/controllers` — **Namespace:** `Camelia\Controllers`
|
||||||
- **PHP** `>=8.3`, extension `json`
|
- **PHP** `>=8.4`, extension `json`
|
||||||
|
|
||||||
## What it is
|
## What it is
|
||||||
|
|
||||||
@@ -33,6 +32,27 @@ own ports; if an application uses an ORM, it connects it by composition.
|
|||||||
composer require camelia/controllers
|
composer require camelia/controllers
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## OpenAPI
|
||||||
|
|
||||||
|
`OpenApi::register()` derives an OpenAPI 3.0 document from the routes already registered on a
|
||||||
|
router and serves it under a prefix:
|
||||||
|
|
||||||
|
```php
|
||||||
|
use Camelia\Controllers\{OpenApi, Router};
|
||||||
|
|
||||||
|
$router = new Router();
|
||||||
|
$router->get('/articulos/{id}', /* handler */);
|
||||||
|
|
||||||
|
OpenApi::register($router, '/docs/', ['title' => 'Facturación', 'version' => '2.0.0']);
|
||||||
|
```
|
||||||
|
|
||||||
|
- `GET /docs/` serves an HTML viewer with the document inline.
|
||||||
|
- `GET /docs/openapi.json` serves the raw document.
|
||||||
|
|
||||||
|
The document describes paths, methods and path parameters. It has no request or response schemas:
|
||||||
|
the library holds no payload metadata, and deriving it here would duplicate what the application
|
||||||
|
already knows.
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
The full developer guide, organised by task, is in
|
The full developer guide, organised by task, is in
|
||||||
@@ -50,6 +70,14 @@ composer check # fmt:check -> lint -> analyze -> phpstan -> test
|
|||||||
|
|
||||||
`composer check` must be green before anything is merged, and the steps run in that order.
|
`composer check` must be green before anything is merged, and the steps run in that order.
|
||||||
|
|
||||||
|
The same gate runs on every commit once the hook is enabled per clone:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git config core.hooksPath .githooks
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `git commit --no-verify` to bypass it for a single commit.
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
MIT. See [LICENSE](LICENSE).
|
MIT. See [LICENSE](LICENSE).
|
||||||
+2
-2
@@ -11,12 +11,12 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"require": {
|
"require": {
|
||||||
"php": ">=8.3",
|
"php": ">=8.4",
|
||||||
"ext-json": "*"
|
"ext-json": "*"
|
||||||
},
|
},
|
||||||
"require-dev": {
|
"require-dev": {
|
||||||
"carthage-software/mago": "^1.60",
|
"carthage-software/mago": "^1.60",
|
||||||
"phpstan/phpstan": "^1.11",
|
"phpstan/phpstan": "2.3",
|
||||||
"phpunit/phpunit": "^10.5 || ^11.0"
|
"phpunit/phpunit": "^10.5 || ^11.0"
|
||||||
},
|
},
|
||||||
"autoload": {
|
"autoload": {
|
||||||
|
|||||||
Generated
+18
-7
@@ -4,7 +4,7 @@
|
|||||||
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
|
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
|
||||||
"This file is @generated automatically"
|
"This file is @generated automatically"
|
||||||
],
|
],
|
||||||
"content-hash": "c828e25914c9dd9e5cf7667b446f40ad",
|
"content-hash": "15c8e8773869cdb0c6dab80f2e5211b7",
|
||||||
"packages": [],
|
"packages": [],
|
||||||
"packages-dev": [
|
"packages-dev": [
|
||||||
{
|
{
|
||||||
@@ -308,15 +308,15 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "phpstan/phpstan",
|
"name": "phpstan/phpstan",
|
||||||
"version": "1.12.34",
|
"version": "2.3.0",
|
||||||
"dist": {
|
"dist": {
|
||||||
"type": "zip",
|
"type": "zip",
|
||||||
"url": "https://api.github.com/repos/phpstan/phpstan/zipball/4dd89ca7aa30fdc6760be21550d583bcc32e8476",
|
"url": "https://api.github.com/repos/phpstan/phpstan/zipball/b1f9890d9af53a25c58129e78f0aadd31f90d7f4",
|
||||||
"reference": "4dd89ca7aa30fdc6760be21550d583bcc32e8476",
|
"reference": "b1f9890d9af53a25c58129e78f0aadd31f90d7f4",
|
||||||
"shasum": ""
|
"shasum": ""
|
||||||
},
|
},
|
||||||
"require": {
|
"require": {
|
||||||
"php": "^7.2|^8.0"
|
"php": "^7.4|^8.0"
|
||||||
},
|
},
|
||||||
"conflict": {
|
"conflict": {
|
||||||
"phpstan/phpstan-shim": "*"
|
"phpstan/phpstan-shim": "*"
|
||||||
@@ -335,6 +335,17 @@
|
|||||||
"license": [
|
"license": [
|
||||||
"MIT"
|
"MIT"
|
||||||
],
|
],
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "Ondřej Mirtes"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Markus Staab"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Vincent Langlet"
|
||||||
|
}
|
||||||
|
],
|
||||||
"description": "PHPStan - PHP Static Analysis Tool",
|
"description": "PHPStan - PHP Static Analysis Tool",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"dev",
|
"dev",
|
||||||
@@ -357,7 +368,7 @@
|
|||||||
"type": "github"
|
"type": "github"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"time": "2026-07-28T10:04:39+00:00"
|
"time": "2026-10-06T06:15:36+00:00"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "phpunit/php-code-coverage",
|
"name": "phpunit/php-code-coverage",
|
||||||
@@ -1967,7 +1978,7 @@
|
|||||||
"prefer-stable": true,
|
"prefer-stable": true,
|
||||||
"prefer-lowest": false,
|
"prefer-lowest": false,
|
||||||
"platform": {
|
"platform": {
|
||||||
"php": ">=8.3",
|
"php": ">=8.4",
|
||||||
"ext-json": "*"
|
"ext-json": "*"
|
||||||
},
|
},
|
||||||
"platform-dev": {},
|
"platform-dev": {},
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
# Mago toolchain configuration — camelia/controllers
|
# Mago toolchain configuration — camelia/controllers
|
||||||
# Docs: https://mago.carthage.software
|
# Docs: https://mago.carthage.software
|
||||||
|
|
||||||
# The library promises PHP >= 8.3. Pinning the parser to 8.2 keeps the formatter from emitting
|
# The library promises PHP >= 8.4.
|
||||||
# syntax the package cannot ship (for example `new Foo()->bar()`, which needs 8.4).
|
php-version = "8.4"
|
||||||
php-version = "8.2"
|
|
||||||
|
|
||||||
[source]
|
[source]
|
||||||
paths = ["src", "tests"]
|
paths = ["src", "tests"]
|
||||||
|
|||||||
Generated
+29
@@ -0,0 +1,29 @@
|
|||||||
|
{
|
||||||
|
"name": "camelia-controllers-dev",
|
||||||
|
"lockfileVersion": 3,
|
||||||
|
"requires": true,
|
||||||
|
"packages": {
|
||||||
|
"": {
|
||||||
|
"name": "camelia-controllers-dev",
|
||||||
|
"devDependencies": {
|
||||||
|
"husky": "^9.1.7"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/husky": {
|
||||||
|
"version": "9.1.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/husky/-/husky-9.1.7.tgz",
|
||||||
|
"integrity": "sha512-5gs5ytaNjBrh5Ow3zrvdUUY+0VxIuWVL4i9irt6friV+BqdCfmV11CQTWMiBYWHbXhco+J1kHfTOUkePhCDvMA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"bin": {
|
||||||
|
"husky": "bin.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/typicode"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"name": "camelia-controllers-dev",
|
||||||
|
"private": true,
|
||||||
|
"description": "Development-only tooling. Not published; the package is installed through Composer.",
|
||||||
|
"scripts": {
|
||||||
|
"prepare": "husky || true"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"husky": "^9.1.7"
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-3
@@ -1,8 +1,7 @@
|
|||||||
parameters:
|
parameters:
|
||||||
level: 8
|
level: 8
|
||||||
# The library promises PHP >= 8.3, so analysis targets the oldest supported version.
|
# The library promises PHP >= 8.4, so analysis targets the only supported version.
|
||||||
# This is why `(new Foo())->bar()` keeps its parentheses: `new Foo()->bar()` only parses on 8.4+.
|
phpVersion: 80400
|
||||||
phpVersion: 80300
|
|
||||||
paths:
|
paths:
|
||||||
- src
|
- src
|
||||||
- tests
|
- tests
|
||||||
|
|||||||
+174
@@ -0,0 +1,174 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Camelia\Controllers;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds an OpenAPI 3.0 document from the routes registered on a router.
|
||||||
|
*
|
||||||
|
* The document describes paths, HTTP methods and path parameters. It does not know request or
|
||||||
|
* response bodies: the library has no schema metadata to derive them from, and inventing one here
|
||||||
|
* would duplicate whatever the application already knows about its own payloads.
|
||||||
|
*
|
||||||
|
* Register it with `OpenApi::register($router, ...)` to serve `GET /docs/` (JSON) and
|
||||||
|
* `GET /docs/openapi.json`.
|
||||||
|
*/
|
||||||
|
final readonly class OpenApi
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param list<array{name: string, in: string, required: bool, schema: array<string, string>}> $parameters
|
||||||
|
*/
|
||||||
|
private function __construct(
|
||||||
|
private Router $router,
|
||||||
|
private string $title,
|
||||||
|
private string $version,
|
||||||
|
private string $description,
|
||||||
|
private string $prefix,
|
||||||
|
private array $parameters,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Serves the document at `{prefix}openapi.json` and a small HTML viewer at `{prefix}`.
|
||||||
|
*
|
||||||
|
* @param array{title?: string, version?: string, description?: string} $info
|
||||||
|
* @param list<string> $pathParameters Names treated as path parameters on every route; defaults
|
||||||
|
* to the parameters each route actually declares.
|
||||||
|
*/
|
||||||
|
public static function register(
|
||||||
|
Router $router,
|
||||||
|
string $prefix = '/docs/',
|
||||||
|
array $info = [],
|
||||||
|
array $pathParameters = [],
|
||||||
|
): self {
|
||||||
|
$document = new self(
|
||||||
|
$router,
|
||||||
|
$info['title'] ?? 'API',
|
||||||
|
$info['version'] ?? '1.0.0',
|
||||||
|
$info['description'] ?? '',
|
||||||
|
$prefix,
|
||||||
|
array_map(static fn(string $name): array => [
|
||||||
|
'name' => $name,
|
||||||
|
'in' => 'path',
|
||||||
|
'required' => true,
|
||||||
|
'schema' => ['type' => 'string'],
|
||||||
|
], $pathParameters),
|
||||||
|
);
|
||||||
|
|
||||||
|
$router->get($prefix . 'openapi.json', static fn(): Response => $document->response());
|
||||||
|
$router->get($prefix, static fn(): Response => $document->htmlResponse());
|
||||||
|
|
||||||
|
return $document;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string, mixed> */
|
||||||
|
public function document(): array
|
||||||
|
{
|
||||||
|
$paths = [];
|
||||||
|
|
||||||
|
foreach ($this->router->routes() as $route) {
|
||||||
|
// The documentation routes are registered on the same router; listing them would make
|
||||||
|
// the document describe itself instead of the application.
|
||||||
|
if (str_starts_with($route->pattern(), $this->prefix)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$path = $route->pattern();
|
||||||
|
$method = strtolower($route->method());
|
||||||
|
$paths[$path][$method] = $this->operation($route);
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'openapi' => '3.0.3',
|
||||||
|
'info' => [
|
||||||
|
'title' => $this->title,
|
||||||
|
'version' => $this->version,
|
||||||
|
'description' => $this->description,
|
||||||
|
],
|
||||||
|
'paths' => $paths,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function response(): Response
|
||||||
|
{
|
||||||
|
return new Response($this->document());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function htmlResponse(): Response
|
||||||
|
{
|
||||||
|
$json = htmlspecialchars(
|
||||||
|
json_encode($this->document(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) ?: '',
|
||||||
|
ENT_QUOTES | ENT_SUBSTITUTE,
|
||||||
|
'UTF-8',
|
||||||
|
);
|
||||||
|
|
||||||
|
$title = htmlspecialchars($this->title, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
|
||||||
|
$description = htmlspecialchars($this->description, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
|
||||||
|
$prefix = htmlspecialchars($this->prefix, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
|
||||||
|
|
||||||
|
$html = <<<HTML
|
||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>{$title}</title>
|
||||||
|
<style>
|
||||||
|
body { font-family: system-ui, sans-serif; margin: 2rem; max-width: 60rem; }
|
||||||
|
h1 { font-size: 1.4rem; } .method { font-weight: 600; text-transform: uppercase; }
|
||||||
|
code { background: #f4f4f4; padding: .1rem .3rem; }
|
||||||
|
pre { background: #f4f4f4; padding: 1rem; overflow: auto; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>{$title}</h1>
|
||||||
|
<p>{$description}</p>
|
||||||
|
<p><a href="{$prefix}openapi.json">OpenAPI JSON</a></p>
|
||||||
|
<pre>{$json}</pre>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
HTML;
|
||||||
|
|
||||||
|
return new Response($html, 200, ['Content-Type' => 'text/html; charset=utf-8']);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The document and the viewer are HTML/JSON, not JSON-only, so the response carries its own
|
||||||
|
* content type instead of relying on the adapter.
|
||||||
|
*
|
||||||
|
* @return array<string, mixed>
|
||||||
|
*/
|
||||||
|
private function operation(Route $route): array
|
||||||
|
{
|
||||||
|
$declared = $route->parameters();
|
||||||
|
$parameters = $declared === []
|
||||||
|
? $this->parameters
|
||||||
|
: array_values(array_filter(
|
||||||
|
$this->parameters,
|
||||||
|
static fn(array $parameter): bool => in_array($parameter['name'], $declared, true),
|
||||||
|
));
|
||||||
|
|
||||||
|
if ($declared !== [] && $parameters === []) {
|
||||||
|
$parameters = array_map(static fn(string $name): array => [
|
||||||
|
'name' => $name,
|
||||||
|
'in' => 'path',
|
||||||
|
'required' => true,
|
||||||
|
'schema' => ['type' => 'string'],
|
||||||
|
], $declared);
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'summary' => $route->method() . ' ' . $route->pattern(),
|
||||||
|
'operationId' => $this->operationId($route),
|
||||||
|
'parameters' => $parameters,
|
||||||
|
'responses' => ['200' => ['description' => 'Successful response']],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function operationId(Route $route): string
|
||||||
|
{
|
||||||
|
$slug = preg_replace('/[^a-zA-Z0-9]+/', '_', trim($route->pattern(), '/')) ?? '';
|
||||||
|
$slug = trim($slug, '_');
|
||||||
|
|
||||||
|
return strtolower($route->method() . '_' . ($slug === '' ? 'root' : $slug));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -61,7 +61,7 @@ final class ArrayGateway implements ResourceGateway
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function count(array $query = []): ?int
|
public function count(array $query = []): int
|
||||||
{
|
{
|
||||||
return count($this->records);
|
return count($this->records);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -158,7 +158,7 @@ final class CrudControllerTest extends TestCase
|
|||||||
|
|
||||||
private function withId(string $method, string $id): Request
|
private function withId(string $method, string $id): Request
|
||||||
{
|
{
|
||||||
return (new JsonRequest(method: $method, path: '/articulos/' . $id))->withAttribute(
|
return new JsonRequest(method: $method, path: '/articulos/' . $id)->withAttribute(
|
||||||
'id',
|
'id',
|
||||||
$id,
|
$id,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ final class JsonRequestTest extends TestCase
|
|||||||
|
|
||||||
public function testWithAttributeKeepsPreviousAttributes(): void
|
public function testWithAttributeKeepsPreviousAttributes(): void
|
||||||
{
|
{
|
||||||
$request = (new JsonRequest())
|
$request = new JsonRequest()
|
||||||
->withAttribute('a', '1')
|
->withAttribute('a', '1')
|
||||||
->withAttribute('b', '2');
|
->withAttribute('b', '2');
|
||||||
|
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ final class ContentNegotiationTest extends TestCase
|
|||||||
|
|
||||||
public function testAddsContentType(): void
|
public function testAddsContentType(): void
|
||||||
{
|
{
|
||||||
$response = (new ContentNegotiation())->process(new JsonRequest(), self::ok(...));
|
$response = new ContentNegotiation()->process(new JsonRequest(), self::ok(...));
|
||||||
|
|
||||||
self::assertSame(200, $response->status());
|
self::assertSame(200, $response->status());
|
||||||
self::assertSame('application/json; charset=utf-8', $response->headers()['Content-Type']);
|
self::assertSame('application/json; charset=utf-8', $response->headers()['Content-Type']);
|
||||||
@@ -27,14 +27,14 @@ final class ContentNegotiationTest extends TestCase
|
|||||||
|
|
||||||
public function testMissingAcceptHeaderIsAccepted(): void
|
public function testMissingAcceptHeaderIsAccepted(): void
|
||||||
{
|
{
|
||||||
$response = (new ContentNegotiation())->process(new JsonRequest(), self::ok(...));
|
$response = new ContentNegotiation()->process(new JsonRequest(), self::ok(...));
|
||||||
|
|
||||||
self::assertSame(200, $response->status());
|
self::assertSame(200, $response->status());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testJsonAcceptIsAccepted(): void
|
public function testJsonAcceptIsAccepted(): void
|
||||||
{
|
{
|
||||||
$response = (new ContentNegotiation())->process(
|
$response = new ContentNegotiation()->process(
|
||||||
new JsonRequest(headers: ['accept' => 'application/json']),
|
new JsonRequest(headers: ['accept' => 'application/json']),
|
||||||
self::ok(...),
|
self::ok(...),
|
||||||
);
|
);
|
||||||
@@ -46,7 +46,7 @@ final class ContentNegotiationTest extends TestCase
|
|||||||
{
|
{
|
||||||
$accept = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
|
$accept = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
|
||||||
|
|
||||||
$response = (new ContentNegotiation())->process(
|
$response = new ContentNegotiation()->process(
|
||||||
new JsonRequest(headers: ['accept' => $accept]),
|
new JsonRequest(headers: ['accept' => $accept]),
|
||||||
self::ok(...),
|
self::ok(...),
|
||||||
);
|
);
|
||||||
@@ -56,7 +56,7 @@ final class ContentNegotiationTest extends TestCase
|
|||||||
|
|
||||||
public function testIncompatibleAcceptIs406(): void
|
public function testIncompatibleAcceptIs406(): void
|
||||||
{
|
{
|
||||||
$response = (new ContentNegotiation())->process(
|
$response = new ContentNegotiation()->process(
|
||||||
new JsonRequest(headers: ['accept' => 'application/xml']),
|
new JsonRequest(headers: ['accept' => 'application/xml']),
|
||||||
static function (): Response {
|
static function (): Response {
|
||||||
self::fail('The handler must not run when the client rejects JSON.');
|
self::fail('The handler must not run when the client rejects JSON.');
|
||||||
@@ -69,7 +69,7 @@ final class ContentNegotiationTest extends TestCase
|
|||||||
|
|
||||||
public function testZeroQualityIsRejected(): void
|
public function testZeroQualityIsRejected(): void
|
||||||
{
|
{
|
||||||
$response = (new ContentNegotiation())->process(
|
$response = new ContentNegotiation()->process(
|
||||||
new JsonRequest(headers: ['accept' => 'application/json;q=0']),
|
new JsonRequest(headers: ['accept' => 'application/json;q=0']),
|
||||||
static function (): Response {
|
static function (): Response {
|
||||||
self::fail('A q=0 entry means not acceptable.');
|
self::fail('A q=0 entry means not acceptable.');
|
||||||
@@ -81,7 +81,7 @@ final class ContentNegotiationTest extends TestCase
|
|||||||
|
|
||||||
public function testNonZeroQualityIsAccepted(): void
|
public function testNonZeroQualityIsAccepted(): void
|
||||||
{
|
{
|
||||||
$response = (new ContentNegotiation())->process(
|
$response = new ContentNegotiation()->process(
|
||||||
new JsonRequest(headers: ['accept' => 'application/json;q=0.5']),
|
new JsonRequest(headers: ['accept' => 'application/json;q=0.5']),
|
||||||
self::ok(...),
|
self::ok(...),
|
||||||
);
|
);
|
||||||
@@ -91,7 +91,7 @@ final class ContentNegotiationTest extends TestCase
|
|||||||
|
|
||||||
public function testExistingContentTypeIsPreserved(): void
|
public function testExistingContentTypeIsPreserved(): void
|
||||||
{
|
{
|
||||||
$response = (new ContentNegotiation())->process(
|
$response = new ContentNegotiation()->process(
|
||||||
new JsonRequest(),
|
new JsonRequest(),
|
||||||
static fn(): Response => new Response(['ok' => true], 200, [
|
static fn(): Response => new Response(['ok' => true], 200, [
|
||||||
'Content-Type' => 'application/problem+json',
|
'Content-Type' => 'application/problem+json',
|
||||||
@@ -103,7 +103,7 @@ final class ContentNegotiationTest extends TestCase
|
|||||||
|
|
||||||
public function testContentTypeCanBeDisabled(): void
|
public function testContentTypeCanBeDisabled(): void
|
||||||
{
|
{
|
||||||
$response = (new ContentNegotiation(addContentType: false))->process(
|
$response = new ContentNegotiation(addContentType: false)->process(
|
||||||
new JsonRequest(),
|
new JsonRequest(),
|
||||||
self::ok(...),
|
self::ok(...),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Camelia\Controllers\Tests\Unit;
|
||||||
|
|
||||||
|
use Camelia\Controllers\JsonRequest;
|
||||||
|
use Camelia\Controllers\OpenApi;
|
||||||
|
use Camelia\Controllers\Response;
|
||||||
|
use Camelia\Controllers\Router;
|
||||||
|
use PHPUnit\Framework\Attributes\Test;
|
||||||
|
use PHPUnit\Framework\TestCase;
|
||||||
|
|
||||||
|
final class OpenApiTest extends TestCase
|
||||||
|
{
|
||||||
|
private function router(): Router
|
||||||
|
{
|
||||||
|
$router = new Router();
|
||||||
|
$router->get('/articulos', static fn(): Response => new Response([]));
|
||||||
|
$router->get('/articulos/{id}', static fn(): Response => new Response([]));
|
||||||
|
$router->post('/articulos', static fn(): Response => new Response([], 201));
|
||||||
|
|
||||||
|
return $router;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[Test]
|
||||||
|
public function it_describes_every_registered_route(): void
|
||||||
|
{
|
||||||
|
$router = $this->router();
|
||||||
|
OpenApi::register($router, '/docs/', ['title' => 'Facturación', 'version' => '2.0.0']);
|
||||||
|
|
||||||
|
$document = $router->dispatch(new JsonRequest(path: '/docs/openapi.json'))->body();
|
||||||
|
|
||||||
|
self::assertSame('3.0.3', $document['openapi']);
|
||||||
|
self::assertSame('Facturación', $document['info']['title']);
|
||||||
|
self::assertSame(['get', 'post'], array_keys($document['paths']['/articulos']));
|
||||||
|
self::assertArrayHasKey('get', $document['paths']['/articulos/{id}']);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[Test]
|
||||||
|
public function it_declares_path_parameters_from_the_pattern(): void
|
||||||
|
{
|
||||||
|
$router = $this->router();
|
||||||
|
OpenApi::register($router);
|
||||||
|
|
||||||
|
$operation = $router
|
||||||
|
->dispatch(new JsonRequest(path: '/docs/openapi.json'))
|
||||||
|
->body()['paths']['/articulos/{id}']['get'];
|
||||||
|
|
||||||
|
self::assertSame(
|
||||||
|
[[
|
||||||
|
'name' => 'id',
|
||||||
|
'in' => 'path',
|
||||||
|
'required' => true,
|
||||||
|
'schema' => ['type' => 'string'],
|
||||||
|
]],
|
||||||
|
$operation['parameters'],
|
||||||
|
);
|
||||||
|
self::assertSame('get_articulos_id', $operation['operationId']);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[Test]
|
||||||
|
public function it_does_not_describe_its_own_documentation_routes(): void
|
||||||
|
{
|
||||||
|
$router = $this->router();
|
||||||
|
OpenApi::register($router, '/docs/');
|
||||||
|
|
||||||
|
$paths = $router->dispatch(new JsonRequest(path: '/docs/openapi.json'))->body()['paths'];
|
||||||
|
|
||||||
|
self::assertArrayNotHasKey('/docs/', $paths);
|
||||||
|
self::assertArrayNotHasKey('/docs/openapi.json', $paths);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[Test]
|
||||||
|
public function it_serves_an_html_viewer_at_the_prefix(): void
|
||||||
|
{
|
||||||
|
$router = $this->router();
|
||||||
|
OpenApi::register($router, '/docs/', ['title' => 'API <b>']);
|
||||||
|
|
||||||
|
$response = $router->dispatch(new JsonRequest(path: '/docs/'));
|
||||||
|
|
||||||
|
self::assertSame(200, $response->status());
|
||||||
|
self::assertSame('text/html; charset=utf-8', $response->headers()['Content-Type']);
|
||||||
|
self::assertStringContainsString('API <b>', (string) $response->body());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -88,7 +88,7 @@ final class BearerAuthTest extends TestCase
|
|||||||
|
|
||||||
public function testRouterRejectsBeforeReachingController(): void
|
public function testRouterRejectsBeforeReachingController(): void
|
||||||
{
|
{
|
||||||
$router = (new Router())->withMiddleware(
|
$router = new Router()->withMiddleware(
|
||||||
new BearerAuth(static fn(string $token): ?array => null),
|
new BearerAuth(static fn(string $token): ?array => null),
|
||||||
);
|
);
|
||||||
$router->get('/x', static fn(): Response => new Response(['leaked' => true]));
|
$router->get('/x', static fn(): Response => new Response(['leaked' => true]));
|
||||||
@@ -101,7 +101,7 @@ final class BearerAuthTest extends TestCase
|
|||||||
|
|
||||||
public function testRouterAllowsValidToken(): void
|
public function testRouterAllowsValidToken(): void
|
||||||
{
|
{
|
||||||
$router = (new Router())->withMiddleware(new BearerAuth(static fn(string $token): array => [
|
$router = new Router()->withMiddleware(new BearerAuth(static fn(string $token): array => [
|
||||||
'id' => 1,
|
'id' => 1,
|
||||||
]));
|
]));
|
||||||
$router->get(
|
$router->get(
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ final class CorsTest extends TestCase
|
|||||||
|
|
||||||
public function testWildcardOriginIsAddedToResponse(): void
|
public function testWildcardOriginIsAddedToResponse(): void
|
||||||
{
|
{
|
||||||
$response = (new Cors())->process(
|
$response = new Cors()->process(
|
||||||
new JsonRequest(headers: ['origin' => 'https://app.test']),
|
new JsonRequest(headers: ['origin' => 'https://app.test']),
|
||||||
self::passThrough(...),
|
self::passThrough(...),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -89,8 +89,8 @@ final class RateLimitTest extends TestCase
|
|||||||
public function testBucketsAreSeparatedByClientAddress(): void
|
public function testBucketsAreSeparatedByClientAddress(): void
|
||||||
{
|
{
|
||||||
$limiter = $this->limiter(1);
|
$limiter = $this->limiter(1);
|
||||||
$first = (new JsonRequest())->withAttribute('client_ip', '10.0.0.1');
|
$first = new JsonRequest()->withAttribute('client_ip', '10.0.0.1');
|
||||||
$second = (new JsonRequest())->withAttribute('client_ip', '10.0.0.2');
|
$second = new JsonRequest()->withAttribute('client_ip', '10.0.0.2');
|
||||||
|
|
||||||
self::assertSame(200, $limiter->process($first, self::passThrough(...))->status());
|
self::assertSame(200, $limiter->process($first, self::passThrough(...))->status());
|
||||||
self::assertSame(200, $limiter->process($second, self::passThrough(...))->status());
|
self::assertSame(200, $limiter->process($second, self::passThrough(...))->status());
|
||||||
|
|||||||
@@ -19,15 +19,12 @@ final class RequireRoleTest extends TestCase
|
|||||||
|
|
||||||
private static function withUser(mixed $user): Request
|
private static function withUser(mixed $user): Request
|
||||||
{
|
{
|
||||||
return (new JsonRequest())->withAttribute('user', $user);
|
return new JsonRequest()->withAttribute('user', $user);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testNoIdentityIs401(): void
|
public function testNoIdentityIs401(): void
|
||||||
{
|
{
|
||||||
$response = (new RequireRole(['admin']))->process(
|
$response = new RequireRole(['admin'])->process(new JsonRequest(), self::passThrough(...));
|
||||||
new JsonRequest(),
|
|
||||||
self::passThrough(...),
|
|
||||||
);
|
|
||||||
|
|
||||||
self::assertSame(401, $response->status());
|
self::assertSame(401, $response->status());
|
||||||
self::assertStringContainsString(
|
self::assertStringContainsString(
|
||||||
|
|||||||
Reference in new issue
Block a user