175 lines
5.9 KiB
PHP
175 lines
5.9 KiB
PHP
<?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));
|
|
}
|
|
}
|