73 lines
2.3 KiB
PHP
73 lines
2.3 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace app\controller;
|
|
|
|
use OpenApi\Annotations as OA;
|
|
use support\Response;
|
|
use WebmanTech\Swagger\Controller\RequiredElementsAttributes\PathItem\OpenapiSpec;
|
|
use WebmanTech\Swagger\DTO\ConfigOpenapiDocDTO;
|
|
use WebmanTech\Swagger\DTO\ConfigSwaggerUiDTO;
|
|
use WebmanTech\Swagger\Helper\JsExpression;
|
|
use WebmanTech\Swagger\Integrations\Response as SwaggerResponse;
|
|
use WebmanTech\Swagger\Overwrite\Generator;
|
|
|
|
final class OpenApiController
|
|
{
|
|
private readonly array $requiredElements;
|
|
|
|
public function __construct()
|
|
{
|
|
$this->requiredElements = [
|
|
'info' => __DIR__ . '/../../vendor/webman-tech/swagger/src/Controller/RequiredElementsAttributes/Info',
|
|
'pathItem' => __DIR__ . '/../../vendor/webman-tech/swagger/src/Controller/RequiredElementsAttributes/PathItem',
|
|
];
|
|
}
|
|
|
|
public function index(string $documentUrl): Response
|
|
{
|
|
$config = ConfigSwaggerUiDTO::fromConfig([
|
|
'data' => [
|
|
'ui_config' => [
|
|
'url' => new JsExpression(json_encode($documentUrl, JSON_THROW_ON_ERROR)),
|
|
],
|
|
],
|
|
]);
|
|
|
|
return SwaggerResponse::create()->renderView($config->view, $config->data, $config->view_path);
|
|
}
|
|
|
|
public function document(array $openapiDocConfig): Response
|
|
{
|
|
$config = ConfigOpenapiDocDTO::fromConfig($openapiDocConfig);
|
|
|
|
$generator = (new Generator($config))->init();
|
|
$config->applyGenerator($generator);
|
|
|
|
$openapi = $generator->generate(
|
|
[$this->requiredElements, $config->getScanSources()],
|
|
validate: false,
|
|
);
|
|
if ($openapi === null) {
|
|
throw new \RuntimeException('OpenAPI document generation failed.');
|
|
}
|
|
if (count($openapi->paths) > 1) {
|
|
$openapi->paths = array_filter(
|
|
$openapi->paths,
|
|
static fn (OA\PathItem $pathItem): bool => $pathItem->path !== OpenapiSpec::EXAMPLE_PATH,
|
|
);
|
|
}
|
|
if ($config->openapi_validate) {
|
|
$openapi->validate();
|
|
}
|
|
|
|
$config->applyModify($openapi);
|
|
[$content, $contentType] = $config->generateWithFormat($openapi);
|
|
|
|
return new Response(200, [
|
|
'Content-Type' => $contentType,
|
|
], $content);
|
|
}
|
|
}
|