phpsymfony

Symfony 7 returns duplicate response


I need some help with a strange problem on Symfony 7.1 that i can not figure out. I set up locally a Symfony project and run with Symfony build-in server on a MacOS host machine, and works just great

{ 
  "my_response" : [
      {
         "attribute" : "value1"
      },
      {
         "attribute" : "value2"
      }
   ]
}

However, the exact same project on a Windows Host machine (at first place) and eventually deployed to a Linux server online, outputs the following result

{ 
  "my_response" : [
      {
         "attribute" : "value1"
      },
      {
         "attribute" : "value2"
      }
   ]
}
{ 
  "my_response" : [
      {
         "attribute" : "value1"
      },
      {
         "attribute" : "value2"
      }
   ]
}

My controller / action looks like this

#[Route('/pathto/apiresponse', name: 'path_to_api')]
public function apiresponse(ApiResponse $apiResponse): Response
{

  $response = new Response();

  $response->setContent(json_encode($apiResponse->retrieveResponse()));

  $response->setStatusCode(Response::HTTP_OK);

  $response->headers->set('Content-Type', 'application/json');

  return $response->send();

}

I have already seen this Symfony json response is returning content twice but i believe my case differs somehow, since it has different response on different environments


Solution

  • I figured out what was going on afterall.

    Symfony's Response send() method is as follows (ref: https://github.com/symfony/symfony/blob/7.2/src/Symfony/Component/HttpFoundation/Response.php )

    /**
     * Sends HTTP headers and content.
     *
     * @param bool $flush Whether output buffers should be flushed
     *
     * @return $this
     */
    public function send(bool $flush = true): static
    {
        $this->sendHeaders();
        $this->sendContent();
    
        if (!$flush) {
            return $this;
        }
    
        if (\function_exists('fastcgi_finish_request')) {
            fastcgi_finish_request();
        } elseif (\function_exists('litespeed_finish_request')) {
            litespeed_finish_request();
        } elseif (!\in_array(\PHP_SAPI, ['cli', 'phpdbg', 'embed'], true)) {
            static::closeOutputBuffers(0, true);
            flush();
        }
    
        return $this;
    }
    

    My stack had fastcgi_finish_request enabled and had as a result to have the "correct" response output, while on the other environments that wasn't enabled, there was the incident with the duplicate output.

    If i had used JsonResponse in the first place i wouldn't have come across this issue.