Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
3 / 3
CRAP
100.00% covered (success)
100.00%
1 / 1
Json
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
3 / 3
5
100.00% covered (success)
100.00%
1 / 1
 encode
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 decode
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 _detectError
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
3
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.7.0
11 */
12
13namespace PrivateBin;
14
15use Exception;
16
17/**
18 * Json
19 *
20 * Provides JSON functions in an object oriented way.
21 */
22class 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    public static function encode($input)
34    {
35        $jsonString = json_encode($input);
36        self::_detectError();
37        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 mixed
48     */
49    public static function decode($input)
50    {
51        $output = json_decode($input, true);
52        self::_detectError();
53        return $output;
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    private static function _detectError()
65    {
66        $errorCode = json_last_error();
67        if ($errorCode === JSON_ERROR_NONE) {
68            return;
69        }
70
71        $message = 'A JSON error occurred';
72        if (function_exists('json_last_error_msg')) {
73            $message .= ': ' . json_last_error_msg();
74        }
75        $message .= ' (' . $errorCode . ')';
76        throw new Exception($message, 90);
77    }
78}