开发者

how to set HTTP_HOST for WebTestCases in Symfony2

My application is generating some absolute links via $this->get('request')->getHost(). Problem is: when I try to run testcases, I get following error message:

[exception] 500 | Internal Server Error | Twig_Error_Runtime

[message] An exception has been thrown during the rendering of a template ("Undefined index: HTTP_HOST") in "::base.html.twig" at line 69.

Somehow it's clear to me that there is no host when calling my app via CLI, but I think there must be a way to prevent Symfony2 fr开发者_高级运维om throwing that error.

Anyone knows how to get rid of it?


You could create the request like this:

$request = Request::create('http://example.com/path');

That will make the HTTP host be set.


Maybe what you could do is to inject the host you need directly in the request headers before calling the getter. The host is retrieved by looking at various parameter values. First, the headers parameter X_FORWARDED_HOST is checked to see if it is set. If it is set, it is returned otherwise the method getHost checks if the headers parameter HOST is set then the if the server parameter SERVER_NAME is set and finally if the server parameter SERVER_ADDR is set.

What you could try is to set the header parameter HOST like this before calling the getHost method:

$request = $this->get('request');
$request->headers->set('HOST', 'yourhosthere');

$request->getHost(); // Should return yourhosthere

That being said, I'm not sure this will solve the problem because the error you mentioning tells us that the template tries to retrieve the value of the index HTTP_HOST but it is not defined. Looking at the methods $request->getHost and $request->getHttpHost, I don't see anything trying to retrieve a value having HTTP_HOST as the index but I could have missed it. Could you post the file ::base.html.twig to see if the problem could be lying there.

Regards, Matt


Thanks guys- your answers lead me into the right direction. This is no Symfony2 issue, as i figured out:

It's just the facebook API PHP wrapper which directly accesses the SERVER parameters. This code solved my issue:

$facebook = $this->container->get('facebook');
$returnUrl = 'http://'.$request->getHost();
$returnUrl .= $this->container->get('router')->generate('_validate_facebook');
$_SERVER['HTTP_HOST'] = $request->getHost();
$_SERVER['REQUEST_URI'] = $request->getRequestUri();

$loginUrl = $facebook->getLoginUrl(array(
        'req_perms' => 'publish_stream',
        'next' => $returnUrl,
        ));

return $loginUrl;

now my app runs from web and CLI again

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜