1
0
Fork 0

Detect and warn JSON encoding failures, refs #3786

pull/3794/merge
Jordi Boggiano 2015-03-05 14:24:43 +00:00
parent 8e6f62e769
commit d9b5c884ba
1 changed files with 28 additions and 0 deletions

View File

@ -184,6 +184,9 @@ class JsonFile
{ {
if (version_compare(PHP_VERSION, '5.4', '>=')) { if (version_compare(PHP_VERSION, '5.4', '>=')) {
$json = json_encode($data, $options); $json = json_encode($data, $options);
if (false === $json) {
self::throwEncodeError(json_last_error());
}
// compact brackets to follow recent php versions // compact brackets to follow recent php versions
if (PHP_VERSION_ID < 50428 || (PHP_VERSION_ID >= 50500 && PHP_VERSION_ID < 50512) || (defined('JSON_C_VERSION') && version_compare(phpversion('json'), '1.3.6', '<'))) { if (PHP_VERSION_ID < 50428 || (PHP_VERSION_ID >= 50500 && PHP_VERSION_ID < 50512) || (defined('JSON_C_VERSION') && version_compare(phpversion('json'), '1.3.6', '<'))) {
@ -195,6 +198,9 @@ class JsonFile
} }
$json = json_encode($data); $json = json_encode($data);
if (false === $json) {
self::throwEncodeError(json_last_error());
}
$prettyPrint = (bool) ($options & self::JSON_PRETTY_PRINT); $prettyPrint = (bool) ($options & self::JSON_PRETTY_PRINT);
$unescapeUnicode = (bool) ($options & self::JSON_UNESCAPED_UNICODE); $unescapeUnicode = (bool) ($options & self::JSON_UNESCAPED_UNICODE);
@ -209,6 +215,28 @@ class JsonFile
return $result; return $result;
} }
private static function throwEncodeError($code)
{
switch ($code) {
case JSON_ERROR_DEPTH:
$msg = 'Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
$msg = 'Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
$msg = 'Unexpected control character found';
break;
case JSON_ERROR_UTF8:
$msg = 'Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
$msg = 'Unknown error';
}
throw new \RuntimeException('JSON encoding failed: '.$msg);
}
/** /**
* Parses json string and returns hash. * Parses json string and returns hash.
* *