JSON.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace Elastica;
  3. use Elastica\Exception\JSONParseException;
  4. /**
  5. * Elastica JSON tools.
  6. */
  7. class JSON
  8. {
  9. /**
  10. * Parse JSON string to an array.
  11. *
  12. * @see http://php.net/manual/en/function.json-decode.php
  13. * @see http://php.net/manual/en/function.json-last-error.php
  14. *
  15. * @param string $args,... JSON string to parse
  16. *
  17. * @throws JSONParseException
  18. *
  19. * @return array PHP array representation of JSON string
  20. */
  21. public static function parse($args/* inherit from json_decode */)
  22. {
  23. // extract arguments
  24. $args = func_get_args();
  25. // default to decoding into an assoc array
  26. if (1 === count($args)) {
  27. $args[] = true;
  28. }
  29. // run decode
  30. $array = call_user_func_array('json_decode', $args);
  31. // turn errors into exceptions for easier catching
  32. if ($error = self::getJsonLastErrorMsg()) {
  33. throw new JSONParseException($error);
  34. }
  35. // output
  36. return $array;
  37. }
  38. /**
  39. * Convert input to JSON string with standard options.
  40. *
  41. * @see http://php.net/manual/en/function.json-encode.php
  42. * @see http://php.net/manual/en/function.json-last-error.php
  43. *
  44. * @param mixed $args,... Target to stringify
  45. *
  46. * @throws JSONParseException
  47. *
  48. * @return string Valid JSON representation of $input
  49. */
  50. public static function stringify($args/* inherit from json_encode */)
  51. {
  52. // extract arguments
  53. $args = func_get_args();
  54. // run encode and output
  55. $string = call_user_func_array('json_encode', $args);
  56. // turn errors into exceptions for easier catching
  57. if ($error = self::getJsonLastErrorMsg()) {
  58. throw new JSONParseException($error);
  59. }
  60. // output
  61. return $string;
  62. }
  63. /**
  64. * Get Json Last Error.
  65. *
  66. * @see http://php.net/manual/en/function.json-last-error.php
  67. * @see http://php.net/manual/en/function.json-last-error-msg.php
  68. * @see https://github.com/php/php-src/blob/master/ext/json/json.c#L308
  69. *
  70. * @return string
  71. */
  72. private static function getJsonLastErrorMsg()
  73. {
  74. return JSON_ERROR_NONE !== json_last_error() ? json_last_error_msg() : false;
  75. }
  76. }