From eb79b0aaad21945b039752ed21c711c6e7e92faf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20Fran=C3=A7a?= Date: Tue, 7 Jan 2025 17:47:58 -0300 Subject: [PATCH] Add option to append version to the end of server url --- config/swagger-ui.php | 5 +++++ .../Controllers/OpenApiJsonController.php | 12 +++++++++++- tests/OpenApiRouteTest.php | 19 +++++++++++++++++++ 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/config/swagger-ui.php b/config/swagger-ui.php index acbe26b..4985f9c 100644 --- a/config/swagger-ui.php +++ b/config/swagger-ui.php @@ -50,6 +50,11 @@ */ 'server_url' => env('APP_URL'), + /* + * Append the version to the end of server url. + */ + 'append_version' => false, + /* * The oauth configuration for the swagger file. */ diff --git a/src/Http/Controllers/OpenApiJsonController.php b/src/Http/Controllers/OpenApiJsonController.php index 0dbdddc..c979473 100644 --- a/src/Http/Controllers/OpenApiJsonController.php +++ b/src/Http/Controllers/OpenApiJsonController.php @@ -11,8 +11,12 @@ class OpenApiJsonController { + private string $versionPath; + public function __invoke(Request $request, string $filename) : JsonResponse { + $this->versionPath = $filename; + $path = implode('/', array_slice($request->segments(), 0, -1)); try { @@ -56,8 +60,14 @@ protected function configureServer(array $file, array $json) : array return $json; } + $url = $file['server_url'] ?? config('app.url'); + + if ($file['append_version']) { + $url = Str::finish($url, '/') . ltrim($this->versionPath, '/'); + } + $json['servers'] = [ - ['url' => $file['server_url'] ?? config('app.url')], + ['url' => $url], ]; return $json; diff --git a/tests/OpenApiRouteTest.php b/tests/OpenApiRouteTest.php index 62ef8ae..09671d8 100644 --- a/tests/OpenApiRouteTest.php +++ b/tests/OpenApiRouteTest.php @@ -48,6 +48,25 @@ public function it_sets_server_to_current_app_url_if_modify_file_is_enabled($ope ->assertJsonPath('servers.0.url', 'http://foo.bar'); } + /** + * @test + * + * @dataProvider openApiFileProvider + */ + public function it_appends_the_version_to_the_end_of_server_url_if_append_version_is_enabled($openApiFile) + { + config()->set('swagger-ui.files.0.versions', ['v1' => $openApiFile]); + config()->set('swagger-ui.files.0.modify_file', true); + config()->set('swagger-ui.files.0.append_version', true); + config()->set('swagger-ui.files.0.server_url', null); + config()->set('app.url', 'http://foo.bar'); + + $this->get('swagger/v1') + ->assertStatus(200) + ->assertJsonCount(1, 'servers') + ->assertJsonPath('servers.0.url', 'http://foo.bar/v1'); + } + /** * @test *