chg: [jsonTool] Properly handle invalid JSON for PHP 7.2 and older

pull/8269/head
Jakub Onderka 2022-04-10 09:38:25 +02:00
parent cb218004b0
commit 9e8608b3d3
2 changed files with 11 additions and 12 deletions

View File

@ -26,7 +26,15 @@ class JsonTool
*/
public static function decode($value)
{
$flags = defined('JSON_THROW_ON_ERROR') ? JSON_THROW_ON_ERROR : 0; // Throw exception on error if supported
return json_decode($value, true, 512, $flags);
if (defined('JSON_THROW_ON_ERROR')) {
// JSON_THROW_ON_ERROR is supported since PHP 7.3
return json_decode($value, true, 512, JSON_THROW_ON_ERROR);
}
$decoded = json_decode($value, true);
if ($decoded === null) {
throw new UnexpectedValueException('Could not parse JSON: ' . json_last_error_msg(), json_last_error());
}
return $decoded;
}
}

View File

@ -3197,16 +3197,7 @@ class AppModel extends Model
*/
public function jsonDecode($json)
{
if (defined('JSON_THROW_ON_ERROR')) {
// JSON_THROW_ON_ERROR is supported since PHP 7.3
$decoded = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
} else {
$decoded = json_decode($json, true);
if ($decoded === null) {
throw new UnexpectedValueException('Could not parse JSON: ' . json_last_error_msg(), json_last_error());
}
}
$decoded = JsonTool::decode($json);
if (!is_array($decoded)) {
throw new UnexpectedValueException('JSON must be array type, get ' . gettype($decoded));
}