【问题标题】:Remove parameters from Symfony 4.4 HttpFoundation\Request and re-generate URL从 Symfony 4.4 HttpFoundation\Request 中删除参数并重新生成 URL
【发布时间】:2020-07-22 14:50:38
【问题描述】:

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

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

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

/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(),但我找不到任何东西。

【问题讨论】:

  • 嗨@yivi!感谢您加入,但我在 1.5 年前发布了这个问题。我会接受你的答案,因为它看起来很可靠,但我无法在 ATM 上测试它。

标签: php symfony symfony-http-foundation


【解决方案1】:

要在 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();

【讨论】:

    【解决方案2】:

    我必须完成这项工作,所以我设计了一个非 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;
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-17
      • 1970-01-01
      • 2021-02-05
      • 1970-01-01
      • 2014-10-25
      • 1970-01-01
      相关资源
      最近更新 更多