1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Stratadox\Json; |
5
|
|
|
|
6
|
|
|
/** |
7
|
|
|
* Parser for json strings; Factory for Json objects. |
8
|
|
|
* |
9
|
|
|
* @author Stratadox |
10
|
|
|
*/ |
11
|
|
|
final class JsonParser implements Parser |
12
|
|
|
{ |
13
|
|
|
private const IMMUTABLE = false; |
14
|
|
|
private const MUTABLE = true; |
15
|
|
|
|
16
|
|
|
/** @var Parser[] Cache for the parsers */ |
17
|
|
|
private static $thatIs = []; |
18
|
|
|
|
19
|
|
|
/** @var bool Whether the resulting Json object should be mutable */ |
20
|
|
|
private $makesMutableJson; |
21
|
|
|
|
22
|
|
|
private function __construct(bool $mutable) |
23
|
|
|
{ |
24
|
|
|
$this->makesMutableJson = $mutable; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Produces a json parser to serve as factory for Json objects. |
29
|
|
|
* |
30
|
|
|
* By default, the parser will produce immutable json objects. |
31
|
|
|
* This method will not always produce a new parser per se, since there are |
32
|
|
|
* only two possible states (mutable of immutable) for the factory, it makes |
33
|
|
|
* little sense to create more instances than those two. |
34
|
|
|
* |
35
|
|
|
* @see Json The factory produces Json objects from input strings. |
36
|
|
|
* @see JsonParser::mutable() |
37
|
|
|
* |
38
|
|
|
* @return Parser A json parser which creates ImmutableJson objects. |
39
|
|
|
*/ |
40
|
|
|
public static function create(): Parser |
41
|
|
|
{ |
42
|
|
|
if (!isset(JsonParser::$thatIs['immutable'])) { |
43
|
|
|
JsonParser::$thatIs['immutable'] = new JsonParser(self::IMMUTABLE); |
44
|
|
|
} |
45
|
|
|
return JsonParser::$thatIs['immutable']; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** @inheritdoc */ |
49
|
|
|
public function mutable(): Parser |
50
|
|
|
{ |
51
|
|
|
return JsonParser::createMutable(); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** @inheritdoc */ |
55
|
|
|
public function immutable(): Parser |
56
|
|
|
{ |
57
|
|
|
return JsonParser::create(); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** @inheritdoc */ |
61
|
|
|
public function from(string $jsonInput): Json |
62
|
|
|
{ |
63
|
|
|
if ($this->makesMutableJson) { |
64
|
|
|
return MutableJson::fromString($jsonInput); |
65
|
|
|
} |
66
|
|
|
return ImmutableJson::fromString($jsonInput); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
private static function createMutable(): Parser |
70
|
|
|
{ |
71
|
|
|
if (!isset(JsonParser::$thatIs['mutable'])) { |
72
|
|
|
JsonParser::$thatIs['mutable'] = new JsonParser(self::MUTABLE); |
73
|
|
|
} |
74
|
|
|
return JsonParser::$thatIs['mutable']; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|