1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90: 91: 92: 93: 94: 95: 96: 97: 98: 99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110:
<?php
namespace MvcCore\Tool;
trait Json {
public static function EncodeJson ($data, $flags = 0, $depth = 512) {
if (!defined('JSON_PRESERVE_ZERO_FRACTION'))
define('JSON_PRESERVE_ZERO_FRACTION', 1024);
$flags |= (
JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT |
JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION
);
if (\PHP_VERSION_ID >= 50500) {
$result = @json_encode($data, $flags, $depth);
} else {
$result = @json_encode($data, $flags);
}
$errorCode = json_last_error();
if ($errorCode == JSON_ERROR_NONE) {
if (PHP_VERSION_ID < 70100)
$result = strtr($result, [
"\xe2\x80\xa8" => '\u2028',
"\xe2\x80\xa9" => '\u2029',
]);
return $result;
}
throw new \RuntimeException(
"[".get_class()."] ".static::getJsonLastErrorMessage($errorCode), $errorCode
);
}
public static function DecodeJson ($jsonStr, $flags = 0, $depth = 512) {
$assoc = ($flags & JSON_OBJECT_AS_ARRAY) != 0;
$result = @json_decode($jsonStr, $assoc, $depth, $flags);
$errorCode = json_last_error();
if ($errorCode == JSON_ERROR_NONE)
return $result;
throw new \RuntimeException(
"[".get_class()."] ".static::getJsonLastErrorMessage($errorCode), $errorCode
);
}
public static function IsJsonString ($jsonStr) {
return !preg_match(
'#[^,:{}\[\]0-9.\\-+Eaeflnr-u \n\r\t]#',
preg_replace(
'#"(\.|[^\\"])*"#',
'',
(string) $jsonStr
)
);
}
protected static function getJsonLastErrorMessage ($jsonErrorCode) {
if (function_exists('json_last_error_msg')) {
return json_last_error_msg();
} else {
static $__jsonErrorMessages = array(
JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded.',
JSON_ERROR_STATE_MISMATCH => 'Occurs with underflow or with the modes mismatch.',
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded.',
JSON_ERROR_SYNTAX => 'Syntax error.',
JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded.'
);
return $__jsonErrorMessages[$jsonErrorCode];
}
}
}