Skip to content

Instantly share code, notes, and snippets.

@Leko
Last active January 5, 2017 06:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Leko/071405900795bfcf980ef7bd237e54d0 to your computer and use it in GitHub Desktop.
Save Leko/071405900795bfcf980ef7bd237e54d0 to your computer and use it in GitHub Desktop.
Utility for PHP built-in functions
<?php
namespace Foundation;
class JSONException extends \Exception {}
/**
* Requirement: PHP >= 5.5.0
*/
class JSON
{
// For JSON::encode
const HEX_QUOT = JSON_HEX_QUOT;
const HEX_TAG = JSON_HEX_TAG;
const HEX_AMP = JSON_HEX_AMP;
const HEX_APOS = JSON_HEX_APOS;
const NUMERIC_CHECK = JSON_NUMERIC_CHECK;
const PRETTY_PRINT = JSON_PRETTY_PRINT;
const UNESCAPED_SLASHES = JSON_UNESCAPED_SLASHES;
const FORCE_OBJECT = JSON_FORCE_OBJECT;
const PRESERVE_ZERO_FRACTION = JSON_PRESERVE_ZERO_FRACTION;
const UNESCAPED_UNICODE = JSON_UNESCAPED_UNICODE;
const PARTIAL_OUTPUT_ON_ERROR = JSON_PARTIAL_OUTPUT_ON_ERROR;
// For JSON::decode
const BIGINT_AS_STRING = JSON_BIGINT_AS_STRING;
/**
* @see http://php.net/manual/ja/function.json-encode.php
*/
public static function encode($value, $options = 0, $depth = 512)
{
$encoded = json_encode($value, $options, $depth);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new JSONException(json_last_error_msg(), json_last_error());
}
return $encoded;
}
/**
* @see http://php.net/manual/ja/function.json-decode.php
*/
public static function decode($json, $assoc = false, $depth = 512, $options = 0)
{
$decoded = json_decode($json, $assoc, $depth, $options);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new JSONException(json_last_error_msg(), json_last_error());
}
return $decoded;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment