Skip to content

Instantly share code, notes, and snippets.

@adrianb93
Last active December 3, 2023 21:15
Show Gist options
  • Save adrianb93/5ec51218a8457f3d36b4c8171ea6739b to your computer and use it in GitHub Desktop.
Save adrianb93/5ec51218a8457f3d36b4c8171ea6739b to your computer and use it in GitHub Desktop.
<?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