-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Json.php
66 lines (57 loc) · 1.66 KB
/
Json.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php
declare(strict_types=1);
namespace SonsOfPHP\Component\Json;
/**
* Json Encoder/Decoder.
*
* Usage:
* // Make it simple to drop in as replacement
* $json = Json::encode($value);
* $object = Json::decode($json);
* $array = Json::decode($json, true);
*
* $jsonObj = new Json();
* $json = $jsonObj->getEncoder()
* ->withDepth(512)
* ->withFlags(JSON_PRETTY_PRINT)
* ->encode($value);
*
* $object = $jsonObj->getDecoder()
* ->withDepth(512)
* ->withFlags(JSON_BIGINT_AS_STRING)
* ->decode($json);
*
* $array = $jsonObj->getDecoder()
* ->withDepth(512)
* ->withFlags(JSON_BIGINT_AS_STRING)
* ->asArray() // same as ->withFlags(JSON_OBJECT_AS_ARRAY)
* ->decode($json);
*
* @author Joshua Estes <[email protected]>
*/
class Json
{
private readonly JsonDecoder $decoder;
private readonly JsonEncoder $encoder;
public function __construct(JsonEncoder $encoder = null, JsonDecoder $decoder = null)
{
$this->encoder = $encoder ?? new JsonEncoder();
$this->decoder = $decoder ?? new JsonDecoder();
}
public function getEncoder(): JsonEncoder
{
return $this->encoder;
}
public function getDecoder(): JsonDecoder
{
return $this->decoder;
}
public static function encode($value, int $flags = null, int $depth = null): string
{
return (new JsonEncoder($flags, $depth))->encode($value);
}
public static function decode(string $json, bool $associative = null, int $depth = null, int $flags = null)
{
return (new JsonDecoder($associative, $depth, $flags))->decode($json);
}
}