-
Notifications
You must be signed in to change notification settings - Fork 111
App::encodeJson(): catch case that preg_replace_callback fails #1540
Copy link
Copy link
Closed
Description
Hi,
I recently managed (don't know how, but not too important) to get this error message:
Logic behind this seems that preg_replace_callback() returns null on failure. We should take care of this.
I'd go for this, WDYT?
public function encodeJson($data, bool $forceObject = false): string
{
$options = JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT;
if ($forceObject) {
$options |= JSON_FORCE_OBJECT;
}
$json = json_encode($data, $options | JSON_THROW_ON_ERROR, 512);
// IMPORTANT: always convert large integers to string, otherwise numbers can be rounded by JS
// replace large JSON integers only, do not replace anything in JSON/JS strings
$jsonLargeNumbers = preg_replace_callback('~(?:"(?:[^"\\\\]+|\\\\.)*")?+\K|(?:\'(?:[^\'\\\\]+|\\\\.)*\')?+\K|(?:^|[{\[,:])'
. '[ \n\r\t]*\K-?[1-9]\d{15,}(?=[ \n\r\t]*(?:$|[}\],:]))~s', function ($matches) {
if ($matches[0] === '' || abs((int) $matches[0]) < (2 ** 53)) {
return $matches[0];
}
return '"' . $matches[0] . '"';
}, $json);
if($jsonLargeNumbers == null) {
return $json;
}
return $jsonLargeNumbers;
}
Reactions are currently unavailable
