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 mixed $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        // default to decoding into an assoc array
27        if (1 === \count($args)) {
28            $args[] = true;
29        }
30
31        // run decode
32        $array = \json_decode(...$args);
33
34        // turn errors into exceptions for easier catching
35        if ($error = self::getJsonLastErrorMsg()) {
36            throw new JSONParseException($error);
37        }
38
39        // output
40        return $array;
41    }
42
43    /**
44     * Convert input to JSON string with standard options.
45     *
46     * @see http://php.net/manual/en/function.json-encode.php
47     * @see http://php.net/manual/en/function.json-last-error.php
48     *
49     * @param mixed $args,... Target to stringify
50     *
51     * @throws JSONParseException
52     *
53     * @return string Valid JSON representation of $input
54     */
55    public static function stringify(...$args/* inherit from json_encode */)
56    {
57        // set defaults
58        isset($args[1]) ? $args[1] |= \JSON_PRESERVE_ZERO_FRACTION : $args[1] = \JSON_PRESERVE_ZERO_FRACTION;
59
60        // run encode and output
61        $string = \json_encode(...$args);
62
63        // turn errors into exceptions for easier catching
64        if ($error = self::getJsonLastErrorMsg()) {
65            throw new JSONParseException($error);
66        }
67
68        // output
69        return $string;
70    }
71
72    /**
73     * Get Json Last Error.
74     *
75     * @see http://php.net/manual/en/function.json-last-error.php
76     * @see http://php.net/manual/en/function.json-last-error-msg.php
77     * @see https://github.com/php/php-src/blob/master/ext/json/json.c#L308
78     *
79     * @return string
80     */
81    private static function getJsonLastErrorMsg()
82    {
83        return \JSON_ERROR_NONE !== \json_last_error() ? \json_last_error_msg() : false;
84    }
85}
86