-
Notifications
You must be signed in to change notification settings - Fork 1
/
json.php
executable file
·96 lines (75 loc) · 2.27 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#!/usr/bin/php
<?php
require_once 'test.php';
require_once 'parser.php';
# JSON
$jNumber = _do(function() {
$number = yield literal('-')->orElse(literal('+'))->orElse(just(''));
$number .= yield takeOf('[0-9]');
if (yield literal('.')->orElse(just(false))) {
$number .= '.'. yield takeOf('[0-9]');
}
if ($number !== '')
return +$number;
});
test($jNumber, '42', [ 42,'']);
test($jNumber, '-42', [ -42,'']);
test($jNumber, '3.14', [ 3.14,'']);
test($jNumber,'-3.14', [-3.14,'']);
$NULL = new stdClass;
$jNull = literal('null')->flatMap(function() use ($NULL) {
return just($NULL);
});
test($jNull, 'null', [$NULL,'']);
$jBool = literal('true')->orElse(literal('false'))->flatMap(function($value) {
return just($value === 'true');
});
test($jBool, 'true', [true,'']);
test($jBool, 'false', [false,'']);
$jString = _do(function() {
yield literal('"');
$value = yield takeOf('[^"]');
yield literal('"');
return $value;
});
test($jString, '""', ["",'']);
test($jString, '"abc"', ["abc",'']);
test($jString, '"abc', []);
test($jString, 'abc"', []);
$jList = _do(function() use (&$jValue) {
yield literal('[');
$items = yield $jValue->separatedBy(literal(','));
yield literal(']');
return $items;
});
$jObject = _do(function() use (&$jValue) {
yield literal('{');
$result = [];
$pair = _do(function() use (&$jValue,&$result) {
$key = yield takeOf('\\w');
yield literal(':');
$value = yield $jValue;
$result[$key] = $value;
return true;
});
yield $pair->separatedBy(literal(','));
yield literal('}');
return $result;
});
$jValue = $jNull->orElse($jBool)->orElse($jNumber)->orElse($jString)->orElse($jList)->orElse($jObject);
test($jValue, '', []);
test($jList, '[]', [ [],'']);
test($jList, '[1]', [ [1],'']);
test($jList, '[1,"test",true,false,null]', [ [1,"test",true,false,$NULL],'']);
test($jList, '[[[1]]]', [ [[[1]]],'']);
test($jObject, '{key:42}', [ ['key' => 42], '']);
test($jObject, '{key:42,test:{test:42}}', [ ['key' => 42, 'test' => ['test' => 42]], '']);
test($jValue,
'{num:-3.14,str:"test",list:[1,2,3]}',
[[
'num' => -3.14,
'str' => "test",
'list' => [1,2,3]
],
'']
);