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