|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Elastica; |
| 4 | + |
| 5 | +use Elastica\Exception\JSONParseException; |
| 6 | + |
| 7 | +/** |
| 8 | + * Elastica JSON tools |
| 9 | + * |
| 10 | + * @package Elastica |
| 11 | + */ |
| 12 | +class JSON |
| 13 | +{ |
| 14 | + /** |
| 15 | + * Parse JSON string to an array |
| 16 | + * |
| 17 | + * @param string $json JSON string to parse |
| 18 | + * @return array PHP array representation of JSON string |
| 19 | + * @link http://php.net/manual/en/function.json-decode.php |
| 20 | + * @link http://www.php.net/manual/en/function.json-last-error.php |
| 21 | + */ |
| 22 | + public static function parse(/* inherit from json_decode */) |
| 23 | + { |
| 24 | + // extract arguments |
| 25 | + $args = func_get_args(); |
| 26 | + |
| 27 | + // default to decoding into an assoc array |
| 28 | + if (sizeof($args) === 1) { |
| 29 | + $args[] = true; |
| 30 | + } |
| 31 | + |
| 32 | + // run decode |
| 33 | + $array = call_user_func_array('json_decode', $args); |
| 34 | + |
| 35 | + // turn errors into exceptions for easier catching |
| 36 | + $error = json_last_error(); |
| 37 | + if ($error !== JSON_ERROR_NONE) { |
| 38 | + throw new JSONParseException($error); |
| 39 | + } |
| 40 | + |
| 41 | + // output |
| 42 | + return $array; |
| 43 | + } |
| 44 | + |
| 45 | + /** |
| 46 | + * Convert input to JSON string with standard options |
| 47 | + * |
| 48 | + * @param mixed check args for PHP function json_encode |
| 49 | + * @return string Valid JSON representation of $input |
| 50 | + * @link http://php.net/manual/en/function.json-encode.php |
| 51 | + */ |
| 52 | + public static function stringify(/* inherit from json_encode */) |
| 53 | + { |
| 54 | + // extract arguments |
| 55 | + $args = func_get_args(); |
| 56 | + |
| 57 | + // allow special options value for Elasticsearch compatibility |
| 58 | + if (sizeof($args) > 1 && $args[1] === 'JSON_ELASTICSEARCH') { |
| 59 | + // Use built in JSON constants if available (php >= 5.4) |
| 60 | + $args[1] = (defined('JSON_UNESCAPED_SLASHES') ? JSON_UNESCAPED_SLASHES : 64) |
| 61 | + | (defined('JSON_UNESCAPED_UNICODE') ? JSON_UNESCAPED_UNICODE : 256); |
| 62 | + } |
| 63 | + |
| 64 | + // run encode and output |
| 65 | + return call_user_func_array('json_encode', $args); |
| 66 | + } |
| 67 | +} |
0 commit comments