Created
August 25, 2015 11:32
-
-
Save code-poel/6c1f4b324ecacef5015f to your computer and use it in GitHub Desktop.
Guzzle's method for "validating" JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Wrapper for JSON decode that implements error detection with helpful error | |
* messages. | |
* | |
* @param string $json JSON data to parse | |
* @param bool $assoc When true, returned objects will be converted into | |
* associative arrays. | |
* @param int $depth User specified recursion depth. | |
* @param int $options Bitmask of JSON decode options. | |
* | |
* @return mixed | |
* @throws \InvalidArgumentException if the JSON cannot be parsed. | |
* @link http://www.php.net/manual/en/function.json-decode.php | |
*/ | |
function json_decode($json, $assoc = false, $depth = 512, $options = 0) | |
{ | |
static $jsonErrors = [ | |
JSON_ERROR_DEPTH => 'JSON_ERROR_DEPTH - Maximum stack depth exceeded', | |
JSON_ERROR_STATE_MISMATCH => 'JSON_ERROR_STATE_MISMATCH - Underflow or the modes mismatch', | |
JSON_ERROR_CTRL_CHAR => 'JSON_ERROR_CTRL_CHAR - Unexpected control character found', | |
JSON_ERROR_SYNTAX => 'JSON_ERROR_SYNTAX - Syntax error, malformed JSON', | |
JSON_ERROR_UTF8 => 'JSON_ERROR_UTF8 - Malformed UTF-8 characters, possibly incorrectly encoded' | |
]; | |
$data = \json_decode($json, $assoc, $depth, $options); | |
if (JSON_ERROR_NONE !== json_last_error()) { | |
$last = json_last_error(); | |
throw new \InvalidArgumentException( | |
'Unable to parse JSON data: ' | |
. (isset($jsonErrors[$last]) ? $jsonErrors[$last] : 'Unknown error') | |
); | |
} | |
return $data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment