-
Notifications
You must be signed in to change notification settings - Fork 0
/
HJSONUtils.php
88 lines (77 loc) · 2.16 KB
/
HJSONUtils.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
<?php
namespace tangible\hjson;
class HJSONUtils
{
public static function tryParseNumber($text, $stopAtNext = null)
{
// Parse a number value.
$number = null;
$string = '';
$leadingZeros = 0;
$testLeading = true;
$at = 0;
$ch = null;
$next = function () use ($text, &$ch, &$at) {
$ch = mb_strlen($text) > $at ? $text[$at] : null;
$at++;
return $ch;
};
$next();
if ($ch === '-') {
$string = '-';
$next();
}
while ($ch !== null && $ch >= '0' && $ch <= '9') {
if ($testLeading) {
if ($ch == '0') {
$leadingZeros++;
} else {
$testLeading = false;
}
}
$string .= $ch;
$next();
}
if ($testLeading) {
$leadingZeros--; // single 0 is allowed
}
if ($ch === '.') {
$string .= '.';
while ($next() !== null && $ch >= '0' && $ch <= '9') {
$string .= $ch;
}
}
if ($ch === 'e' || $ch === 'E') {
$string .= $ch;
$next();
if ($ch === '-' || $ch === '+') {
$string .= $ch;
$next();
}
while ($ch !== null && $ch >= '0' && $ch <= '9') {
$string .= $ch;
$next();
}
}
// skip white/to (newline)
while ($ch !== null && $ch <= ' ') {
$next();
}
if ($stopAtNext) {
// end scan if we find a control character like ,}] or a comment
if ($ch === ',' || $ch === '}' || $ch === ']' ||
$ch === '#' || $ch === '/' && ($text[$at] === '/' || $text[$at] === '*')) {
$ch = null;
}
}
$number = $string;
if (is_numeric($string)) {
$number = 0+$string;
}
if ($ch !== null || $leadingZeros || !is_numeric($number)) {
return null;
} else {
return $number;
}
}
}