LaravelでSwagger UIをホスティングしたりOpenAPIファイルを生成してくれるようになるL5-Swaggerですが、公開環境ではSwagger UIのホスティングを無効にしておきたい。
ドキュメントを読んでもやり方が書いてなかったので、ソースコードを読んで調べた方法をメモ。
環境
- PHP: 8.1.3
- Laravel: 9.47.0
- darkaonline/l5-swagger: 8.4.1
方法
L5-Swaggerのコンフィグでroutesをnullにする。
以下の例ではAPP_DEBUGの値に応じて切り替えるようにしてます。
config/l5-swagger.php
<?php
return [
'default' => 'default',
'documentations' => [
'default' => [
'api' => [
'title' => 'L5 Swagger UI',
],
'routes' => env('APP_DEBUG') ? [
/*
* Route for accessing api documentation interface
*/
'api' => 'api/documentation',
] : null,
'paths' => [
// **** 省略 ****
解説
L5-Swaggerでルーティングしているコードはvendor/darkaonline/l5-swagger/src/routes.phpにあります。routesがissetで評価されているので、nullを入れてあげればルーティングをスキップできます。ミドルウェアなどで制御する必要もありませんでした。
routes.php
<?php
use Illuminate\Routing\Router;
use Illuminate\Support\Facades\Route;
use L5Swagger\ConfigFactory;
use L5Swagger\Http\Middleware\Config as L5SwaggerConfig;
Route::group(['namespace' => 'L5Swagger'], function (Router $router) {
$configFactory = resolve(ConfigFactory::class);
$documentations = config('l5-swagger.documentations', []);
foreach (array_keys($documentations) as $name) {
$config = $configFactory->documentationConfig($name);
if (! isset($config['routes'])) {
continue;
}
$groupOptions = $config['routes']['group_options'] ?? [];
// **** 省略 ****