diff --git a/README.md b/README.md index d00687a..cb05c4b 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/src/OpenApi.php b/src/OpenApi.php new file mode 100644 index 0000000..e817bf6 --- /dev/null +++ b/src/OpenApi.php @@ -0,0 +1,174 @@ +}> $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 $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 */ + 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 = << + + + + {$title} + + + +

{$title}

+

{$description}

+

OpenAPI JSON

+
{$json}
+ + + 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 + */ + 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)); + } +} diff --git a/tests/Unit/OpenApiTest.php b/tests/Unit/OpenApiTest.php new file mode 100644 index 0000000..56883c1 --- /dev/null +++ b/tests/Unit/OpenApiTest.php @@ -0,0 +1,86 @@ +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 ']); + + $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()); + } +}