<?php
declare(strict_types=1);
namespace App\Action;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
/**
* Class RedirectAction
*
* @author André Varelmann <andre.varelmann@bestit-online.de>
* @package App\Action
*/
class RedirectAction
{
/**
* Redirects to a given target route
*
* @param string $path
* @param bool $permanent
*
* @return RedirectResponse
*/
public function __invoke(
string $path,
bool $permanent = false,
?Request $request = null,
): RedirectResponse
{
if (isset($request)) {
$allQueryParams = $request->query->all();
if (!empty($allQueryParams) && !str_contains($path, '?')) {
$path .= '?' . http_build_query($allQueryParams);
}
}
return new RedirectResponse(
$path,
$permanent ? 301 : 302
);
}
}