<?php

namespace Tricks\LaravelTools\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CompressMiddleware
{
    /** @phpstan-ignore missingType.return */
    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);

        if (in_array('gzip', $request->getEncodings()) && function_exists('gzencode')) {
            $response->header('Content-Encoding', 'gzip');
            $response->header('Vary', 'Accept-Encoding');
            $response->setContent(gzencode($response->content(), 9));
        }

        return $response;
    }
}
