Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
71.43% covered (warning)
71.43%
10 / 14
50.00% covered (danger)
50.00%
1 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
GzipResponse
71.43% covered (warning)
71.43%
10 / 14
50.00% covered (danger)
50.00%
1 / 2
6.84
0.00% covered (danger)
0.00%
0 / 1
 handle
69.23% covered (warning)
69.23%
9 / 13
0.00% covered (danger)
0.00%
0 / 1
5.73
 acceptsGzip
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3namespace App\Http\Middleware;
4
5use Closure;
6use Illuminate\Http\Request;
7use Illuminate\Http\Response;
8use Symfony\Component\HttpFoundation\BinaryFileResponse;
9
10class GzipResponse
11{
12    /**
13     * Handle an incoming request.
14     *
15     * @return mixed
16     */
17    public function handle(Request $request, Closure $next)
18    {
19        ini_set('memory_limit', '-1');
20
21        // Proceed to get the response
22        $response = $next($request);
23
24        // Check if the response is an instance of BinaryFileResponse (file download)
25        if ($response instanceof BinaryFileResponse) {
26            // Skip gzip compression for file download responses (binary files)
27            return $response;
28        }
29
30        // Check if the response content is an array or object (e.g., JSON response)
31        if (is_array($response->getOriginalContent()) || is_object($response->getOriginalContent())) {
32            // Convert the array to JSON
33            $content = json_encode($response->getOriginalContent(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
34
35            // If the client accepts gzip and the response content is JSON, apply gzip compression
36            if ($this->acceptsGzip($request)) {
37                // Compress the content using gzencode
38                $gzippedContent = gzencode($content, 9); // Highest compression level (9)
39
40                // Set the compressed content in the response
41                $response->setContent($gzippedContent);
42
43                // Set the appropriate headers for Gzip encoding
44                $response->headers->set('Content-Encoding', 'gzip');
45            } else {
46                // If not gzipped, just set the plain JSON content
47                $response->setContent($content);
48            }
49
50            // Set Content-Type header to application/json
51            $response->headers->set('Content-Type', 'application/json');
52        }
53
54        return $response;
55    }
56
57    /**
58     * Check if the client accepts Gzip encoding.
59     *
60     * @return bool
61     */
62    private function acceptsGzip(Request $request)
63    {
64        return strpos($request->header('Accept-Encoding'), 'gzip') !== false;
65    }
66}