Get the environment inside the controller

I have a situation in one of my controllers that should only be accessed through AJAX, I have the following code.

if (!$request->isXmlHttpRequest()) { $response = new Response(); $response->setContent('AJAX requests only!'); return $response; } 

When I test, this gives me a problem because the request was not actually made through AJAX. Then it interrupts my tests every time. How do I work on this?

My ideas:

  • I tried to set the server header, but had no success.
  • Check if I am in the test environment in the controller and do not check it. I know this is dirty, but it will work .: - / The problem was that I could not understand how to find out in which environment I live.

Does anyone have any other ideas or tips that I don’t have enough to work on one of the above?

+6
ajax symfony testing phpunit controller
source share
2 answers

Considering the isXmlHttpRequest code in the Request class and the getHeaders method in the ServerBag class, the code snippet below should do the trick:

 $client->request( 'GET', '/path/to/test', array(), array(), array( 'HTTP_X-Requested-With' => 'XMLHttpRequest', ) ); 

I have not tested it personally, but I think it should work. The line of code below in Request used to check if the HTTP request is XmlHttpRequest .

 return 'XMLHttpRequest' == $this->headers->get('X-Requested-With'); 

In the code, $this->headers installed using:

 $this->headers = new HeaderBag($this->server->getHeaders()); 

The getHeaders method creates an array of headers. Each server variable starting with HTTP_ , plus some special server variables, such as CONTENT_TYPE , are placed in this array.

Hope this helps.

Yours faithfully,
Matt

+5
source share

Of course, in the case of Icode4food it is better to use the Matt solution, but here's how to find the current environment:

 $this->container->getParameter('kernel.environment') 
+8
source share

All Articles