PageRenderTime 23ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Elastica/JSON.php

http://github.com/ruflin/Elastica
PHP | 66 lines | 27 code | 9 blank | 30 comment | 4 complexity | 1535a8bda6e7fc417cfb3ae28e5e9602 MD5 | raw file
  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. * @link http://php.net/manual/en/function.json-decode.php
  13. * @link http://php.net/manual/en/function.json-last-error.php
  14. *
  15. * @param string $json JSON string to parse
  16. *
  17. * @return array PHP array representation of JSON string
  18. */
  19. public static function parse(/* inherit from json_decode */)
  20. {
  21. // extract arguments
  22. $args = func_get_args();
  23. // default to decoding into an assoc array
  24. if (count($args) === 1) {
  25. $args[] = true;
  26. }
  27. // run decode
  28. $array = call_user_func_array('json_decode', $args);
  29. // turn errors into exceptions for easier catching
  30. $error = json_last_error();
  31. if ($error !== JSON_ERROR_NONE) {
  32. throw new JSONParseException($error);
  33. }
  34. // output
  35. return $array;
  36. }
  37. /**
  38. * Convert input to JSON string with standard options.
  39. *
  40. * @link http://php.net/manual/en/function.json-encode.php
  41. *
  42. * @param mixed check args for PHP function json_encode
  43. *
  44. * @return string Valid JSON representation of $input
  45. */
  46. public static function stringify(/* inherit from json_encode */)
  47. {
  48. // extract arguments
  49. $args = func_get_args();
  50. // allow special options value for Elasticsearch compatibility
  51. if (count($args) > 1 && $args[1] === 'JSON_ELASTICSEARCH') {
  52. $args[1] = JSON_UNESCAPED_UNICODE;
  53. }
  54. // run encode and output
  55. return call_user_func_array('json_encode', $args);
  56. }
  57. }