<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class NormalizeSignedUrlParameters
{
    public function handle(Request $request, Closure $next)
    {
        $queryString = $request->server->get('QUERY_STRING');

        if (is_string($queryString) && str_contains($queryString, '&amp;')) {
            $normalized = str_replace('&amp;', '&', $queryString);

            if ($normalized !== $queryString) {
                $request->server->set('QUERY_STRING', $normalized);
                parse_str($normalized, $params);

                if (is_array($params) && ! empty($params)) {
                    $request->query->replace(array_merge($request->query->all(), $params));
                }
            }
        }

        return $next($request);
    }
}
