Passed
Branch master (c976c6)
by Théo
03:51
created

json.php ➔ json_decode()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 12
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 4
dl 12
loc 12
ccs 0
cts 5
cp 0
crap 6
rs 9.8666
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the humbug/php-scoper package.
7
 *
8
 * Copyright (c) 2017 Théo FIDRY <[email protected]>,
9
 *                    Pádraic Brady <[email protected]>
10
 *
11
 * For the full copyright and license information, please view the LICENSE
12
 * file that was distributed with this source code.
13
 */
14
15
// Safe JSON functions; ensures the encode/decode always throws an exception on error.
16
// This code can be removed once 7.3.0 is required as a minimal version by leveraging
17
// JSON_THROW_ON_ERROR.
18
19
namespace Humbug\PhpScoper {
20
    use JsonException;
21
    use function error_clear_last;
22
    use function json_decode as original_json_decode;
23
    use function json_encode as original_json_encode;
24
    use function json_last_error;
25
    use function json_last_error_msg as original_json_last_error_msg;
26
27
    /**
28
     * @throws JsonException
29
     *
30
     * @return object|array
31
     */
32
    function json_decode(string $json, bool $assoc = false, int $depth = 512, int $options = 0)
33
    {
34
        error_clear_last();
35
36
        $result = original_json_decode($json, $assoc, $depth, $options);
37
38
        if (null === $result) {
39
            throw create_json_exception();
40
        }
41
42
        return $result;
43
    }
44
45
    function json_encode($value, int $options = 0, int $depth = 512): string
46
    {
47
        error_clear_last();
48
49
        $result = original_json_encode($value, $options, $depth);
50
51
        if (false === $result) {
52
            throw create_json_exception();
53
        }
54
55
        return $result;
56
    }
57
58
    /**
59
     * @internal
60
     */
61
    function create_json_exception(): JsonException
62
    {
63
        return new JsonException(original_json_last_error_msg(), json_last_error());
64
    }
65
}
66
67
namespace {
68
    if (false === class_exists(JsonException::class, false)) {
69
        class JsonException extends Exception
70
        {
71
        }
72
    }
73
}
74