从 Symfony 4.4 中删除参数 HttpFoundation\Request 并重新生成 URL

Remove parameters from Symfony 4.4 HttpFoundation\Request and re-generate URL

我需要重新生成我页面的 URL,删除附加参数。例如:当我收到:

/bao1/bao2/?removeMe1=anything&keepMe1=anything&removeMe2=&keepMe2=anything

我想生成 URL 并删除 removeMe 查询变量,但其他所有内容都完好无损。像这样:

/bao1/bao2/?keepMe1=anything&keepMe2=anything

我自动连接了请求:

public function __construct(RequestStack $httpRequest)
{
   $this->httpRequest = $httpRequest;
}

那我就这样玩:

public function getCleanUrl()
{
   // HttpFoundation\Request 
   $currentHttpRequest = $this->httpRequest->getCurrentRequest();

   // Trying to remove the parameters
   $currentHttpRequest->query->remove("removeMe1");

   return $currentHttpRequest->getUri()
}

query->remove("removeMe1") 有效,但是当我调用 getUri() 时,我仍然得到完整的输入 url,就好像 remove() 从未被调用过一样。我想我可能缺少调用某种 $currentHttpRequest->regenerate()->getUri() 但我找不到任何东西。

我必须完成这项工作,所以我设计了一个非 Symfony 解决方案:

$currentHttpRequest = $this->httpRequest->getCurrentRequest();

$arrParams          = $currentHttpRequest->query->all();
$arrParams          = array_intersect_key($arrParams, array_flip([
    "keepMe1", "keepMe2"
]));

$currentUrlNoQs     = strtok($currentHttpRequest->getUri(), '?');

if( empty($arrParams) ) {

    $canonical          = $currentUrlNoQs;

} else {

    $queryString        = http_build_query($arrParams);
    $canonical          = $currentUrlNoQs . '?' . $queryString;
}

return $canonical;

我不太喜欢它,但它完成了工作。

要在 Request 对象上调用 mutator 方法后获得修改后的 URL,您需要调用 overrideGlobals().

如果没有,Request 方法将根据原始超全局变量($_GET$_POST$_SERVER)为您提供结果。通过调用 Request::overrideGlobals() 你告诉对象不要这样做。

例如:

if ($request->query->has('amp') && Request::METHOD_GET === $request->getMethod()) {
   $request->query->remove('amp');
   $request->overrideGlobals();

   return new RedirectResponse($request->getUri(), Response::HTTP_MOVED_PERMANENTLY));
}

或者,更适合您的用例的东西(未经测试,但总体思路应该成立):

$queryParams = array_keys($request->query->all());
$goodParams = ['foo', 'bar', 'baz'];

$badParams = array_diff($queryParams, $goodParams);

foreach ($badParams as $badParam) {
    $request->query->remove($badParam);
}

$request->overrideGlobals();

// get modified URL
echo $request->getUri();