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     * @param  \Illuminate\Http\Request  $request
16     * @param  \Closure  $next
17     * @return mixed
18     */
19    public function handle(Request $request, Closure $next)
20    {
21        ini_set('memory_limit', '-1');
22
23        // Proceed to get the response
24        $response = $next($request);
25
26        // Check if the response is an instance of BinaryFileResponse (file download)
27        if ($response instanceof BinaryFileResponse) {
28            // Skip gzip compression for file download responses (binary files)
29            return $response;
30        }
31
32        // Check if the response content is an array or object (e.g., JSON response)
33        if (is_array($response->getOriginalContent()) || is_object($response->getOriginalContent())) {
34            // Convert the array to JSON
35            $content = json_encode($response->getOriginalContent(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
36
37            // If the client accepts gzip and the response content is JSON, apply gzip compression
38            if ($this->acceptsGzip($request)) {
39                // Compress the content using gzencode
40                $gzippedContent = gzencode($content, 9); // Highest compression level (9)
41
42                // Set the compressed content in the response
43                $response->setContent($gzippedContent);
44
45                // Set the appropriate headers for Gzip encoding
46                $response->headers->set('Content-Encoding', 'gzip');
47            } else {
48                // If not gzipped, just set the plain JSON content
49                $response->setContent($content);
50            }
51
52            // Set Content-Type header to application/json
53            $response->headers->set('Content-Type', 'application/json');
54        }
55
56        return $response;
57    }
58
59    /**
60     * Check if the client accepts Gzip encoding.
61     *
62     * @param \Illuminate\Http\Request $request
63     * @return bool
64     */
65    private function acceptsGzip(Request $request)
66    {
67        return strpos($request->header('Accept-Encoding'), 'gzip') !== false;
68    }
69}