Passed
Pull Request — master (#431)
by El
03:04
created

Json::decode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * PrivateBin
4
 *
5
 * a zero-knowledge paste bin
6
 *
7
 * @link      https://github.com/PrivateBin/PrivateBin
8
 * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
9
 * @license   https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
10
 * @version   1.2.1
11
 */
12
13
namespace PrivateBin;
14
15
use Exception;
16
17
/**
18
 * Json
19
 *
20
 * Provides JSON functions in an object oriented way.
21
 */
22
class Json
23
{
24
    /**
25
     * Returns a string containing the JSON representation of the given input
26
     *
27
     * @access public
28
     * @static
29
     * @param  mixed $input
30
     * @throws Exception
31
     * @return string
32
     */
33 89
    public static function encode($input)
34
    {
35 89
        $jsonString = json_encode($input);
36 89
        self::_detectError();
37 88
        return $jsonString;
38
    }
39
40
    /**
41
     * Returns an array with the contents as described in the given JSON input
42
     *
43
     * @access public
44
     * @static
45
     * @param  string $input
46
     * @throws Exception
47
     * @return array
48
     */
49 106
    public static function decode($input)
50
    {
51 106
        $array = json_decode($input, true);
52 106
        self::_detectError();
53 104
        return $array;
54
    }
55
56
    /**
57
     * Detects JSON errors and raises an exception if one is found
58
     *
59
     * @access private
60
     * @static
61
     * @throws Exception
62
     * @return void
63
     */
64 117
    private static function _detectError()
65
    {
66 117
        $errorCode = json_last_error();
67 117
        if ($errorCode === JSON_ERROR_NONE) {
68 114
            return;
69
        }
70
71 4
        $message = 'A JSON error occurred';
72 4
        if (function_exists('json_last_error_msg')) {
73 4
            $message .= ': ' . json_last_error_msg();
74
        }
75 4
        $message .= ' (' . $errorCode . ')';
76 4
        throw new Exception($message, 90);
77
    }
78
}
79