[HttpFoundation] Silent only JSON errors

This commit is contained in:
Jerome TAMARELLE 2014-07-18 15:26:18 +02:00 committed by Fabien Potencier
parent 4fa670bfae
commit ddf95c7adc
2 changed files with 41 additions and 1 deletions

View File

@ -95,7 +95,20 @@ class JsonResponse extends Response
*/
public function setData($data = array())
{
$this->data = @json_encode($data, $this->encodingOptions);
$errorHandler = null;
$errorHandler = set_error_handler(function () use (&$errorHandler) {
if (JSON_ERROR_NONE !== json_last_error()) {
return;
}
if ($errorHandler) {
call_user_func_array($errorHandler, func_get_args());
}
});
$this->data = json_encode($data, $this->encodingOptions);
restore_error_handler();
if (JSON_ERROR_NONE !== json_last_error()) {
throw new \InvalidArgumentException($this->transformJsonError());

View File

@ -201,4 +201,31 @@ class JsonResponseTest extends \PHPUnit_Framework_TestCase
{
JsonResponse::create("\xB1\x31");
}
/**
* @expectedException PHPUnit_Framework_Error_Warning
* @expectedExceptionMessage This error is expected
*/
public function testSetContentJsonSerializeError()
{
if (!interface_exists('JsonSerializable')) {
$this->markTestSkipped('Interface JsonSerializable is available in PHP 5.4+');
}
$serializable = new JsonSerializableObject();
JsonResponse::create($serializable);
}
}
if (interface_exists('JsonSerializable')) {
class JsonSerializableObject implements JsonSerializable
{
public function jsonSerialize()
{
trigger_error('This error is expected', E_USER_WARNING);
return array();
}
}
}