问题
I have a situation in one of my controllers that should only be accessed via AJAX, I have the following code.
if (!$request->isXmlHttpRequest()) {
$response = new Response();
$response->setContent('AJAX requests only!');
return $response;
}
When I am testing this gives me an issue because the request hasn't actually been made via AJAX. This then breaks my tests every time. How should I go about working around this?
My Ideas:
- I have tried to set a server header but have had absolutely no success.
- Check if I am in the test environment in the controller and don't do the check if it is. I know this is dirty, but it would work. :-/ The problem was that I couldn't figure out how to discover what environment I am in.
Anyone else have any other ideas or tips that I am missing to get one of the above to work?
回答1:
Looking at the code for isXmlHttpRequest
in class Request
and method getHeaders
in class ServerBag
, the piece of code below should do the trick:
$client->request(
'GET',
'/path/to/test',
array(),
array(),
array(
'HTTP_X-Requested-With' => 'XMLHttpRequest',
)
);
I did not test it personally but I think it should works. The line of code below in Request
is used to check if the http request is a XmlHttpRequest
.
return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
In the code, $this->headers
is set using:
$this->headers = new HeaderBag($this->server->getHeaders());
The method getHeaders
creates an array of headers. Each server variable starting with HTTP_
, plus some special server variables like CONTENT_TYPE
, are put in this array.
Hope this helps.
Regards,
Matt
回答2:
Of course in Icode4food's case, it's better to use Matt's solution, but here is how to find the current environment:
$this->container->getParameter(‘kernel.environment’)
来源:https://stackoverflow.com/questions/8272090/get-environment-inside-controller