Skip to content

Instantly share code, notes, and snippets.

@cbonnissent
Created March 26, 2013 13:17
Show Gist options
  • Save cbonnissent/5245289 to your computer and use it in GitHub Desktop.
Save cbonnissent/5245289 to your computer and use it in GitHub Desktop.
JsonHandler
<?php
class JsonHandler
{
protected static $_messages = array(
JSON_ERROR_NONE => 'No error has occurred',
JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON',
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'
);
public static function encode($value, $options = 0)
{
$result = json_encode($value, $options);
if ($result !== false) {
return $result;
}
throw new RuntimeException(static::$_messages[json_last_error()]);
}
public static function encodeForHTML($value, $options = 0)
{
if ($options === 0) {
$options = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP;
}
return self::encode($value, $options);
}
public static function decode($json, $assoc = false)
{
$result = json_decode($json, $assoc);
if ($result !== false) {
return $result;
}
throw new RuntimeException(static::$_messages[json_last_error()]);
}
public static function decodeAsArray($json)
{
return self::decode($json, true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment