| 1: | <?php |
| 2: | namespace Worldline\Connect\Sdk\JSON; |
| 3: | |
| 4: | use stdClass; |
| 5: | use UnexpectedValueException; |
| 6: | |
| 7: | |
| 8: | |
| 9: | |
| 10: | |
| 11: | |
| 12: | class JSONUtil |
| 13: | { |
| 14: | private function __construct() |
| 15: | { |
| 16: | } |
| 17: | |
| 18: | |
| 19: | |
| 20: | |
| 21: | |
| 22: | |
| 23: | public static function decode($value) |
| 24: | { |
| 25: | $object = json_decode($value); |
| 26: | if (json_last_error()) { |
| 27: | throw new UnexpectedValueException('Invalid JSON value: ' . self::getLastJsonDecodeErrorString()); |
| 28: | } |
| 29: | return $object; |
| 30: | } |
| 31: | |
| 32: | |
| 33: | |
| 34: | |
| 35: | public static function getLastJsonDecodeErrorString() |
| 36: | { |
| 37: | if (function_exists('json_last_error_msg')) { |
| 38: | return json_last_error_msg(); |
| 39: | } |
| 40: | switch (json_last_error()) { |
| 41: | case JSON_ERROR_NONE: |
| 42: | return 'No errors'; |
| 43: | case JSON_ERROR_DEPTH: |
| 44: | return 'Maximum stack depth exceeded'; |
| 45: | case JSON_ERROR_STATE_MISMATCH: |
| 46: | return 'Underflow or the modes mismatch'; |
| 47: | case JSON_ERROR_CTRL_CHAR: |
| 48: | return 'Unexpected control character found'; |
| 49: | case JSON_ERROR_SYNTAX: |
| 50: | return 'Syntax error. Malformed JSON'; |
| 51: | case JSON_ERROR_UTF8: |
| 52: | return 'Malformed UTF-8 characters. Incorrect encoding'; |
| 53: | default: |
| 54: | return 'Unknown error'; |
| 55: | } |
| 56: | } |
| 57: | } |
| 58: | |