Closed
Description
Symfony version(s) affected: 4.2.5
Description
JsonResponse::setData
checks json_last_error
to determine whether or not encoding was successful, however when JSON_THROW_ON_ERROR
is set as an encoding option, the error state is not cleared.
This means when a previous JSON operation that does not use JSON_THROW_ON_ERROR
has failed, JsonResponse::setData
will throw an exception even when the encode operation was successful.
How to reproduce
<?php declare(strict_types=1);
require 'vendor/autoload.php';
$response = new \Symfony\Component\HttpFoundation\JsonResponse();
$response->setEncodingOptions(JSON_THROW_ON_ERROR);
// Commenting this out prevents the exception from setData
json_decode('bad data, but carry on');
$response->setData('this is fine');
PHP Fatal error: Uncaught InvalidArgumentException: Syntax error in /var/www/html/vendor/symfony/http-foundation/JsonResponse.php:152
Stack trace:
#0 /var/www/html/test.php(12): Symfony\Component\HttpFoundation\JsonResponse->setData('"this is fine"')
#1 {main}
thrown in /var/www/html/vendor/symfony/http-foundation/JsonResponse.php on line 152
Possible Solution
Check encoding options for JSON_THROW_ON_ERROR
when checking json_last_error()
Additional context