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