This commit is contained in:
1 parent
afcb2e8449
commit
f83d36e64f
3 files changed
+281
No files matched your search
@@ -33,6 +33,27 @@ own ports; if an application uses an ORM, it connects it by composition.
|
||||
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
|
||||
|
||||
The full developer guide, organised by task, is in
|
||||
|
||||
+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));
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user