From b5afc6f3b989562eef0a9c090745914959004ca8 Mon Sep 17 00:00:00 2001 From: Pulkit Kathuria Date: Fri, 2 Feb 2024 13:53:15 +0900 Subject: [PATCH] fixes #327 gzip failed to fetch --- src/LaravelRequestDocsMiddleware.php | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/src/LaravelRequestDocsMiddleware.php b/src/LaravelRequestDocsMiddleware.php index 6d9ab34..8e2746a 100644 --- a/src/LaravelRequestDocsMiddleware.php +++ b/src/LaravelRequestDocsMiddleware.php @@ -81,16 +81,29 @@ public function handle(Request $request, Closure $next): Response $jsonContent = json_encode($content); if (in_array('gzip', $request->getEncodings()) && function_exists('gzencode')) { - $level = 9; // best compression; - $jsonContent = gzencode($jsonContent, $level); + $level = 9; // Best compression. + $compressedContent = gzencode($jsonContent, $level); + + // Create a new response object with compressed content. + $response = new Response($compressedContent); + + // Add necessary headers. $response->headers->add([ - 'Content-type' => 'application/json; charset=utf-8', - 'Content-Length' => strlen($jsonContent), + 'Content-Type' => 'application/json; charset=utf-8', + 'Content-Length' => strlen($compressedContent), 'Content-Encoding' => 'gzip', ]); + + return $response; // Return the response object directly. + } else { + // Fallback for clients that do not support gzip. + $response = new Response($jsonContent); + $response->headers->add([ + 'Content-Type' => 'application/json; charset=utf-8', + ]); + + return $response; } - $response->setContent($jsonContent); - return $response; } public function listenToDB(): void