Description
Consider when creating a JsonResponse
and calling setContent()
instead of setData()
(bypassing this->data
and meant for adding serialized content straight onto $this->content
and skipping the added json_encode feature.
$jsonData = '{...}'; // something something
$response = new JsonResponse();
$response->setContent($jsonData)
$response->setEncodingOptions(JSON_PRETTY_PRINT); // some encoding option
return $response;
This will return an empty string as the JsonResponse content. Of course when setting content manually, there is no need for setting options anymore. However it's not always clear when data or content is passed to a JsonResponse. Inside the setEncodingOptions()
:
// Symfony\Component\HttpFoundation/JsonReponse.php
public function setEncodingOptions($encodingOptions)
{
$this->encodingOptions = (int) $encodingOptions;
return $this->setData(json_decode($this->data));
}
This also triggers the re-adding of this->data
as content. I think this leads to enexpected behaviour. This proposal might not be the prettiest, but it works:
// Symfony\Component\HttpFoundation/JsonReponse.php
public function setEncodingOptions($encodingOptions)
{
$this->encodingOptions = (int)$encodingOptions;
if ($this->content !== null) {
$this->data = $this->content;
}
return $this->setData(json_decode($this->data));
}
Another option to get rid of this issue is when calling setContent()
, try to set and isFinal flag or something.
// Symfony\Component\HttpFoundation/JsonReponse.php
public function setContent($content)
{
$this->data = json_decode($content);
// call Symfony\Component\HttpFoundation/Reponse.php
parent::setContent($content);
}