<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;

class GzipCompression
{
    /**
     * Handle an incoming request.
     *
     * @param  Closure(Request): (Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);

        if (
            $response instanceof StreamedResponse ||
            $response instanceof BinaryFileResponse
        ) {
            return $response;
        }

        if (
            extension_loaded('zlib') &&
            str_contains($request->header('Accept-Encoding'), 'gzip') &&
            function_exists('gzencode') &&
            ! $response->headers->has('Content-Encoding')
        ) {
            $content = $response->getContent();
            $compressedContent = gzencode($content, 6);

            if ($compressedContent !== false) {
                $response->setContent($compressedContent);
                $response->headers->add([
                    'Content-Encoding' => 'gzip',
                    'Content-Length' => strlen($compressedContent),
                    'X-Compressed' => 'true',
                ]);
            }
        }

        return $response;
    }
}
