Оптимизация работы с Unicode в json

This commit is contained in:
Антон Н. Николаев
2021-01-15 09:16:39 +03:00
parent 13b8b4b611
commit 1e1f3743d8
6 changed files with 42 additions and 6 deletions
+25 -3
View File
@@ -265,13 +265,35 @@ class BaseClient
return '{}';
}
$result = json_encode($serializedData);
if ($result === false) {
if (defined('JSON_UNESCAPED_UNICODE')) {
$encoded = json_encode($serializedData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} else {
$encoded = self::_unescaped(json_encode($serializedData));
}
if ($encoded === false) {
$errorCode = json_last_error();
throw new JsonException("Failed serialize json.", $errorCode);
}
return $result;
return $encoded;
}
/**
* @param string $json
* @return string|false
*/
private static function _unescaped($json)
{
if ($json === false) {
return false;
}
$json = str_replace('\\/', '/', $json);
return preg_replace_callback('/\\\\u(\w{4})/', function ($matches) {
return html_entity_decode('&#x' . $matches[1] . ';', ENT_COMPAT, 'UTF-8');
}, $json);
}
/**