Json::encode()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 9
rs 10
cc 2
nc 2
nop 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gnumoksha\FreeIpa\Infra\Json;
6
7
use function json_decode;
8
use function json_encode;
9
10
/**
11
 * This class is a wrapper around php built-in functions json_encode and json_decode.
12
 *
13
 * It is useful because it throws an exception if the operation fails, as consequence the
14
 * returned values will not be null.
15
 *
16
 * @internal
17
 */
18
final class Json
19
{
20
    /**
21
     * Encode a value as json.
22
     *
23
     * @param mixed $value
24
     *
25
     * @throws \Gnumoksha\FreeIpa\Infra\Json\JsonException
26
     * @see \json_encode()
27
     */
28
    public static function encode($value, int $options = 0, int $depth = 512): string
29
    {
30
        $encoded = json_encode($value, $options, $depth);
31
32
        if (json_last_error() !== JSON_ERROR_NONE) {
33
            throw new JsonException(sprintf('Unable to encode json. Error was: "%s".', json_last_error_msg()));
34
        }
35
36
        return (string)$encoded;
37
    }
38
39
    /**
40
     * Decode a value from json.
41
     *
42
     * @return mixed[]|\stdClass
43
     * @throws \Gnumoksha\FreeIpa\Infra\Json\JsonException
44
     * @see \json_decode()
45
     */
46
    public static function decode(string $json, bool $assoc = false, int $depth = 512, int $options = 0)
47
    {
48
        $decoded = json_decode($json, $assoc, $depth, $options);
49
50
        if (json_last_error() !== JSON_ERROR_NONE) {
51
            throw new JsonException(sprintf('Unable to decode json. Error was: "%s".', json_last_error_msg()));
52
        }
53
54
        return $decoded;
55
    }
56
}
57