Last active
December 3, 2023 21:15
-
-
Save adrianspacely/5ec51218a8457f3d36b4c8171ea6739b to your computer and use it in GitHub Desktop.
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 | |
if (! function_exists('json_validate')) { | |
/** | |
* Validate a json string. | |
* | |
* @param string $json | |
* @param boolean $throw | |
* @return boolean | |
* @throws \InvalidArgumentException | |
*/ | |
function json_validate($json, $throw = false) | |
{ | |
$result = json_decode($json); | |
$errorCode = json_last_error(); | |
$valid = $errorCode === JSON_ERROR_NONE; | |
if ($valid === false && $throw) { | |
$messages = [ | |
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, malformed JSON.', | |
JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded.', | |
JSON_ERROR_RECURSION => 'One or more recursive references in the value to be encoded.', | |
JSON_ERROR_INF_OR_NAN => 'One or more NAN or INF values in the value to be encoded.', | |
JSON_ERROR_UNSUPPORTED_TYPE => 'A value of a type that cannot be encoded was given.', | |
]; | |
throw new InvalidArgumentException( | |
$messages[$errorCode] ?? 'Unknown JSON error occured.' | |
); | |
} | |
return $valid; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment