Skip to content

Instantly share code, notes, and snippets.

@devdrops
Created October 4, 2016 18:08
Show Gist options
  • Select an option

  • Save devdrops/788c17f766dd8abf3f1223e8dbfba48c to your computer and use it in GitHub Desktop.

Select an option

Save devdrops/788c17f766dd8abf3f1223e8dbfba48c to your computer and use it in GitHub Desktop.
JSON helper for PHP
<?php
namespace \Json
class Helper
{
/**
* @var array
*/
protected $errorReference = [
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.',
// These last 3 messages are only supported on PHP >= 5.5.
// See http://php.net/json_last_error#refsect1-function.json-last-error-returnvalues
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.',
];
/**
* @var string
*/
const JSON_UNKNOWN_ERROR = 'Unknown error.';
/**
* Provides the error message, related to json_last_error().
*
* If the error code is not found, returns a default `Unknown error` message.
*
* @param int $errorCode Return from json_last_error()
*
* @return string The error message.
*/
public static function getLastErrorMessage($errorCode)
{
if (!array_key_exists($errorCode, $this->errorReference)) {
return self::JSON_UNKNOWN_ERROR;
}
return $this->errorReference[$errorCode];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment