×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: PHP
Posted by: Matt Parry
Added: Jul 14, 2017 6:16 PM
Views: 8
Tags: no tags
simple OOP wrapper for encoding and decoding JSON
  1. class Json
  2. {
  3.     private static $messages = array(
  4.         JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
  5.         JSON_ERROR_STATE_MISMATCH => 'Syntax error, malformed JSON',
  6.         JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
  7.         JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON',
  8.         5 /*JSON_ERROR_UTF8*/ => 'Invalid UTF-8 sequence',
  9.         6 /*JSON_ERROR_RECURSION*/ => 'Recursion detected',
  10.         7 /*JSON_ERROR_INF_OR_NAN*/ => 'Inf and NaN cannot be JSON encoded',
  11.         8 /*JSON_ERROR_UNSUPPORTED_TYPE*/ => 'Type is not supported',
  12.     );
  13.  
  14.  
  15.     public static function encode($value)
  16.     {
  17.         // needed to receive 'Invalid UTF-8 sequence' error; PHP bugs #52397, #54109, #63004
  18.         if (function_exists('ini_set')) { // ini_set is disabled on some hosts :-(
  19.             $old = ini_set('display_errors', 0);
  20.         }
  21.  
  22.         // needed to receive 'recursion detected' error
  23.         set_error_handler(function($severity, $message) {
  24.             restore_error_handler();
  25.             throw new JsonException($message);
  26.         });
  27.  
  28.         $json = json_encode($value);
  29.  
  30.         restore_error_handler();
  31.         if (isset($old)) {
  32.             ini_set('display_errors', $old);
  33.         }
  34.         if ($error = json_last_error()) {
  35.             $message = isset(static::$messages[$error]) ? static::$messages[$error] : 'Unknown error';
  36.             throw new JsonException($message, $error);
  37.         }
  38.         return $json;
  39.     }
  40.  
  41.  
  42.     public static function decode($json)
  43.     {
  44.         if (!preg_match('##u', $json)) { // workaround for PHP < 5.3.3 & PECL JSON-C
  45.             throw new JsonException('Invalid UTF-8 sequence', 5);
  46.         }
  47.  
  48.         $value = json_decode($json);
  49.  
  50.         if ($value === NULL
  51.             && $json !== ''  // it doesn't clean json_last_error flag until 5.3.7
  52.             && $json !== 'null' // in this case NULL is not failure
  53.         ) {
  54.             $error = json_last_error();
  55.             $message = isset(static::$messages[$error]) ? static::$messages[$error] : 'Unknown error';
  56.             throw new JsonException($message, $error);
  57.         }
  58.         return $value;
  59.     }
  60. }