JSON::encode()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
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 3
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types = 1);
3
/**
4
 * /src/Utils/JSON.php
5
 *
6
 * @author TLe, Tarmo Leppänen <[email protected]>
7
 */
8
9
namespace App\Utils;
10
11
use JsonException;
12
use function json_decode;
13
use function json_encode;
14
15
/**
16
 * Class JSON
17
 *
18
 * @package App\Util
19
 * @author TLe, Tarmo Leppänen <[email protected]>
20
 */
21
class JSON
22
{
23
    /**
24
     * Generic JSON encode method with error handling support.
25
     *
26
     * @see http://php.net/manual/en/function.json-encode.php
27
     * @see http://php.net/manual/en/function.json-last-error.php
28
     *
29
     * @param mixed $input The value being encoded. Can be any type except a resource.
30
     * @param int|null $options Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS,
31
     *                          JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT,
32
     *                          JSON_PRESERVE_ZERO_FRACTION, JSON_UNESCAPED_UNICODE, JSON_PARTIAL_OUTPUT_ON_ERROR.
33
     *                          The behaviour of these constants is described on the JSON constants page.
34
     * @param int<1, 2147483647>|null $depth Set the maximum depth. Must be greater than zero.
35
     *
36
     * @throws JsonException
37
     */
38 568
    public static function encode(mixed $input, ?int $options = null, ?int $depth = null): string
39
    {
40 568
        $options ??= 0;
41 568
        $depth ??= 512;
42
43 568
        return json_encode($input, JSON_THROW_ON_ERROR | $options, $depth);
44
    }
45
46
    /**
47
     * Generic JSON decode method with error handling support.
48
     *
49
     * @see http://php.net/manual/en/function.json-decode.php
50
     * @see http://php.net/manual/en/function.json-last-error.php
51
     *
52
     * @param string $json the json string being decoded
53
     * @param bool|null $assoc when TRUE, returned objects will be converted into associative arrays
54
     * @param int<1, 2147483647>|null $depth Set the maximum depth. Must be greater than zero.
55
     * @param int|null $options Bitmask of JSON decode options. Currently only JSON_BIGINT_AS_STRING is supported
56
     *                          (default is to cast large integers as floats)
57
     *
58
     * @throws JsonException
59
     */
60 731
    public static function decode(string $json, ?bool $assoc = null, ?int $depth = null, ?int $options = null): mixed
61
    {
62 731
        $assoc ??= false;
63 731
        $depth ??= 512;
64 731
        $options ??= 0;
65
66 731
        return json_decode($json, $assoc, $depth, JSON_THROW_ON_ERROR | $options);
67
    }
68
}
69