note 104467 deleted from function.json-last-error by danbrown
| From: | danbrown@php.net | Date: | Thu, 16 Jun 2011 17:01:15 +0000 |
| Subject: | note 104467 deleted from function.json-last-error by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-180620@lists.php.net to get a copy of this message | ||
Note Submitter: ryan dot pendergast at gmail dot com
----
Making lior's class a little more robust:
<?php
/**
*
* JSON wrapper class that handles JSON encoding/decoding errors.
*
* @see http://us.php.net/manual/en/function.json-last-error.php
*
* @author rynop http://rynop.com
*
*/
class JSON
{
/**
*
* Encode String to JSON
* @param mixed $obj
* @return string JSON representation
* @throws Exception
*/
public static function Encode($obj)
{
$result = json_encode($obj);
self::checkForErrors();
return $result;
}
/**
*
* Decodes a JSON string
* @param string $json
* @param boolean $toAssoc
* @return Object JSON Object
* @throws Exception
*/
public static function Decode($json, $toAssoc = false)
{
$result = json_decode($json, $toAssoc);
self::checkForErrors();
return $result;
}
private static function checkForErrors(){
$code = json_last_error();
switch($code)
{
case JSON_ERROR_DEPTH:
$error = 'Maximum stack depth exceeded';
break;
case JSON_ERROR_CTRL_CHAR:
$error = 'Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
$error = 'Syntax error, malformed JSON';
break;
case JSON_ERROR_STATE_MISMATCH:
$error = 'Invalid or malformed JSON';
break;
case JSON_ERROR_NONE:
default:
$error = '';
}
if (!empty($error)){
throw new Exception('JSON Error: '.$error,$code);
}
}
}
?>