-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathJSON.php
547 lines (508 loc) · 12.6 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
<?php
/**
* Handle encoding and decoding of JSON from resp. to native PHP data structures.
*
* @package CMB
* @copyright Copyright (c) 2012-2013 Christoph M. Becker <http://3-magi.net/>
* @license http://www.gnu.org/licenses/gpl-3.0.en.html GNU GPLv3
* @version $Id: JSON.php 252 2014-10-16 16:56:25Z hi $
*/
/**
* End of string has been reached.
*
* @access private
*/
define('CMB_JSON_EOS', -1);
/**
* Unknown terminal symbol.
*
* @access private
*/
define('CMB_JSON_UNKNOWN', 0);
/**
* <kbd>NUMBER</kbd>
*
* @access private
*/
define('CMB_JSON_NUMBER', 1);
/**
* <kbd>STRING</kbd>
*
* @access private
*/
define('CMB_JSON_STRING', 2);
/**
* <kbd>LBRACE</kbd>
*
* @access private
*/
define('CMB_JSON_LBRACE', 3);
/**
* <kbd>RBRACE</kbd>
*
* @access private
*/
define('CMB_JSON_RBRACE', 4);
/**
* <kbd>LBRACK</kbd>
*
* @access private
*/
define('CMB_JSON_LBRACK', 5);
/**
* <kbd>RBRACK</kbd>
*
* @access private
*/
define('CMB_JSON_RBRACK', 6);
/**
* <kbd>COMMA</kbd>
*
* @access private
*/
define('CMB_JSON_COMMA', 7);
/**
* <kbd>COLON</kbd>
* @access private
*/
define('CMB_JSON_COLON', 8);
/**
* <kdb>TRUE</kbd>
*
* @access private
*/
define('CMB_JSON_TRUE', 9);
/**
* <kbd>FALSE</kbd>
*
* @access private
*/
define('CMB_JSON_FALSE', 10);
/**
* <kbd>NULL</kbd>
*
* @access private
*/
define('CMB_JSON_NULL', 11);
/**
* Handles encoding and decoding of JSON from resp. to native PHP data structures.
*
* It is a <i>simplified</i> alternative to <kbd>json_encode()</kbd> and <kbd>json_decode()</kbd>
* that can be used as fallback for ancient PHP versions.
*
* @package CMB
*/
class CMB_JSON
{
/**
* The set of "first" tokens.
*
* @access private
*
* @var array
*/
var $first;
/**
* The string to parse.
*
* Already parsed parts will be truncated.
*
* @access private
*
* @var string
*/
var $str;
/**
* The current token.
*
* @access private
*
* @var int
*/
var $sym;
/**
* The current value (for strings and numbers).
*
* @access private
*
* @var mixed
*/
var $value;
/**
* Error flag.
*
* @access private
*
* @var bool
*/
var $error;
/**
* Constructor.
*
* @access private
*/
function CMB_JSON()
{
$this->first = array(
'object' => array(CMB_JSON_LBRACE),
'pair' => array(CMB_JSON_STRING),
'array' => array(CMB_JSON_LBRACK),
'value' => array(CMB_JSON_STRING, CMB_JSON_NUMBER,
CMB_JSON_LBRACE, CMB_JSON_LBRACK,
CMB_JSON_TRUE, CMB_JSON_FALSE,
CMB_JSON_NULL));
}
/**
* Quotes a string for use as JSON string.
*
* @access private
*
* @param string $string
* @return string
*/
function quote($string)
{
$string = addcslashes($string, "\"\\");
$string = preg_replace('/[\x00-\x1f]/s', '\u00$1', $string);
return $string;
}
/**
* Returns UTF-8 chars for JSON unicode escape sequence.
*
* Ignores BOM and illegal surrogates.
*
* @access private
*
* @param array $matches
* @return string
*/
function unescape($matches)
{
$n = hexdec($matches[1]);
if ($n >= 0 && $n <= 0x007f) {
return chr($n);
} elseif ($n <= 0x07ff) {
return chr(0xc0 | ($n >> 6))
. chr(0x80 | ($n & 0x003f));
} elseif($n == 0xfeff) {
return ''; // skip BOM
} elseif ($n >= 0xd800 && $n <= 0xdfff) {
// TODO: what to do here?
return '';
} else {
return chr(0xe0 | ($n >> 12))
. chr(0x80 | (($n >> 6) & 0x003f))
. chr(0x80 | ($n & 0x003f));
}
}
/**
* Scans the next token and sets $this->sym accordingly.
*
* @access private
*
* @return void
*/
function getSym()
{
$this->str = preg_replace('/^\s*/', '', $this->str); // TODO: all UTF-8 whitespace
if (empty($this->str)) {
$this->sym = CMB_JSON_EOS;
return;
}
switch ($this->str{0}) {
case '-': case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
preg_match('/-?(?:0|[1-9][0-9]*(?:\.[0-9]+)?(?:[eE][-+]?[0-9]+)?)/',
$this->str, $m);
$i = intval($m[0]);
$this->value = $i == $m[0] ? $i : floatval($m[0]);
$this->str = substr($this->str, strlen($m[0]));
$this->sym = CMB_JSON_NUMBER;
break;
case '"':
preg_match('/^"((?:[^"\\\\]|[\\\\](?:["\\\\\/bfnrt]|u[0-9a-fA-F]{4}))*)/',
$this->str, $m);
$m[1] = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/',
array($this, 'unescape'),
$m[1]);
$this->value = stripcslashes($m[1]);
$this->str = substr($this->str, strlen($m[0]) + 1);
$this->sym = CMB_JSON_STRING;
break;
case '{':
$this->str = substr($this->str, 1);
$this->sym = CMB_JSON_LBRACE;
break;
case '}':
$this->str = substr($this->str, 1);
$this->sym = CMB_JSON_RBRACE;
break;
case '[':
$this->str = substr($this->str, 1);
$this->sym = CMB_JSON_LBRACK;
break;
case ']':
$this->str = substr($this->str, 1);
$this->sym = CMB_JSON_RBRACK;
break;
case ',':
$this->str = substr($this->str, 1);
$this->sym = CMB_JSON_COMMA;
break;
case ':':
$this->str = substr($this->str, 1);
$this->sym = CMB_JSON_COLON;
break;
case 't':
if (strpos($this->str, 'true') === 0) {
$this->str = substr($this->str, 4);
$this->sym = CMB_JSON_TRUE;
} else {
$this->sym = CMB_JSON_UNKNOWN;
}
break;
case 'f':
if (strpos($this->str, 'false') === 0) {
$this->str = substr($this->str, 5);
$this->sym = CMB_JSON_FALSE;
} else {
$this->sym = CMB_JSON_UNKNOWN;
}
break;
case 'n':
if (strpos($this->str, 'null') === 0) {
$this->str = substr($this->str, 4);
$this->sym = CMB_JSON_NULL;
} else {
$this->sym = CMB_JSON_UNKNOWN;
}
break;
default:
$this->sym = CMB_JSON_UNKNOWN;
}
}
/**
* Expect and consume a terminal symbol.
*
* Set <var>$error</var> to true, if symbol was not found.
*
* @access private
*
* @param string $terminal
* @return void
*/
function accept($terminal)
{
if ($this->sym != $terminal) {
$this->error = true;
}
$this->getSym();
}
/**
* Parse an object.
*
* <samp>object -> LBRACE [ pair { COMMA pair ] RBRACE</samp>
*
* @access private
*
* @param object &$res
* @return void
*/
function parseObject(&$res)
{
$this->accept(CMB_JSON_LBRACE);
$res = array();
if (in_array($this->sym, $this->first['pair'])) {
$this->parsePair($key, $val);
$res[$key]= $val;
while ($this->sym == CMB_JSON_COMMA) {
$this->accept(CMB_JSON_COMMA);
$this->parsePair($key, $val);
$res[$key] = $val;
}
}
$this->accept(CMB_JSON_RBRACE);
}
/**
* Parse a pair.
*
* <samp>pair -> STRING COLON value</samp>
*
* @access private
*
* @param string &$key
* @param mixed &$val
* @return void
*/
function parsePair(&$key, &$val)
{
$this->accept(CMB_JSON_STRING);
$key = $this->value;
$this->accept(CMB_JSON_COLON);
$this->parseValue($val);
}
/**
* Parse an array.
*
* <samp>array -> LBRACK [ value { COMMA value } ] RBRACK</samp>
*
* @access private
*
* @param array &$res
* @return void
*/
function parseArray(&$res)
{
$this->accept(CMB_JSON_LBRACK);
$res = array();
if (in_array($this->sym, $this->first['value'])) {
$this->parseValue($res1);
$res[] = $res1;
while ($this->sym == CMB_JSON_COMMA) {
$this->accept(CMB_JSON_COMMA);
$this->parseValue($res1);
$res[] = $res1;
}
}
$this->accept(CMB_JSON_RBRACK);
}
/**
* Parse a value.
*
* <samp>value -> STRING | NUMBER | object | array | TRUE | FALSE | NULL</samp>
*
* @access private
*
* @param mixed &$res
* @return void
*/
function parseValue(&$res)
{
switch ($this->sym) {
case CMB_JSON_STRING:
$res = $this->value;
$this->getSym();
break;
case CMB_JSON_NUMBER:
$res = $this->value;
$this->getSym();
break;
case CMB_JSON_LBRACE:
$this->parseObject($res);
break;
case CMB_JSON_LBRACK:
$this->parseArray($res);
break;
case CMB_JSON_TRUE:
$res = true;
$this->getSym();
break;
case CMB_JSON_FALSE:
$res = false;
$this->getSym();
break;
case CMB_JSON_NULL:
$res = null;
$this->getSym();
break;
}
}
/**
* Returns a PHP value encoded as JSON string.
*
* <kbd>encode($value)</kbd> should be equivalent to
* <kbd>json_encode($value, JSON_UNESCAPED_SLASHES
* | JSON_UNESCAPED_UNICODE)</kbd>.
*
* @access public
*
* @param mixed $value
* @return string
*/
function encode($value)
{
switch (gettype($value)) {
case 'boolean':
return $value ? 'true' : 'false';
case 'integer':
case 'double':
return $value;
case 'string':
return '"' . $this->quote($value) . '"';
case 'array':
if (array_keys($value) === range(0, count($value) - 1)) {
// encode as array
$elts = array();
foreach ($value as $val) {
$elts[] = $this->encode($val);
}
return '[' . implode(',', $elts) . ']';
} else {
// encode as object
$members = array();
foreach ($value as $key => $val) {
$members[] = '"' . $this->quote($key) . '":'
. $this->encode($val);
}
return '{' . implode(',', $members) . '}';
}
case 'object':
return $this->encode(get_object_vars($value));
case 'NULL':
return 'null';
default:
$msg = __FUNCTION__ . '(): type is unsupported, encoded as null';
trigger_error($msg, E_USER_WARNING);
return 'null';
}
}
/**
* Returns the JSON string decoded as PHP value.
*
* <kbd>decode($string)</kbd> should be equivalent to
* <kbd>json_decode($string, true)</kbd> for valid UTF-8.
*
* If the input is erroneous, NULL is returned. To distinguish this from
* a real NULL value, use {@link CMB_JSON::lastError()}.
*
* @access public
*
* @param string $string
* @return mixed
*/
function decode($string)
{
$this->str = $string;
$this->sym = $this->value = null;
$this->error = false;
$this->getSym();
$this->parseValue($res);
return $this->error ? null : $res;
}
/**
* Returns whether an error has occurred during the last {@link CMB_JSON::decode()}.
*
* @access public
*
* @return bool
*/
function lastError()
{
return $this->error;
}
/**
* Returns the unique instance of the class.
*
* @access public
*
* @return object
*/
function instance()
{
static $instance;
if (!isset($instance)) {
$instance = new CMB_JSON();
}
return $instance;
}
}