-
Notifications
You must be signed in to change notification settings - Fork 2
/
JsParser.php
116 lines (90 loc) · 3 KB
/
JsParser.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
<?php
class JsParserException extends Exception {}
class JsParser {
/**
* Decode a JSON / javascript variable definition into a PHP equivalent
* e.g. "{test:5}" returns array('test' => 5);
* "false" returns false
* @param string $str
* @return mixed
*/
public static function doParse($str) {
return self::parse($str);
}
public static function parse(&$str) {
$str = ltrim($str);
if ('[' == $str[0]) {
return self::parseArray($str);
}
if ('{' == $str[0]) {
return self::parseObj($str);
}
if ('"' == $str[0] || "'" == $str[0]) {
if (!preg_match("@^".$str[0]."([^".$str[0]."]*)".$str[0]."@i", $str, $matches)) {
throw new JsParserException("Missing end token for string");
}
$str = ltrim(substr($str, strlen($matches[0])));
return $matches[1];
}
if (preg_match("@^\d\.?\d*@", $str, $matches)) {
$str = ltrim(substr($str, strlen($matches[0])));
return $matches[0];
}
if (stripos($str, 'true') === 0) {
$str = ltrim(substr($str, 4));
return true;
}
if (stripos($str, 'false') === 0) {
$str = ltrim(substr($str, 5));
return false;
}
if (stripos($str, 'null') === 0) {
$str = ltrim(substr($str, 4));
return null;
}
if (stripos($str, 'undefined') === 0) {
$str = ltrim(substr($str, 9));
return null;
}
throw new JsParserException("Unexpected token '".$str[0]."'");
}
protected static function parseArray(&$str) {
$ret = array();
$str = ltrim(substr($str, 1));
while (']' !== $str[0]) {
$parsedSection = self::parse($str);
$ret[] = $parsedSection;
if (',' == $str[0]) {
$str = ltrim(substr($str, 1));
} else {
break;
}
}
if (']' != $str[0]) {
throw new JsParserException("Unexpected token '".$str[0]."' expected ]");
}
$str = ltrim(substr($str, 1));
return $ret;
}
protected static function parseObj(&$str) {
$ret = array();
$str = ltrim(substr($str, 1));
while ('}' !== $str[0]) {
if (!preg_match('/^"?([a-zA-z_][a-zA-Z_\d]*)"?\s*:/', $str, $matches)) {
throw new JsParserException("Unexpected token '".$str[0]."' expecting object key");
}
$str = ltrim(substr($str, strlen($matches[0])));
$ret[$matches[1]] = self::parse($str);
if (',' == $str[0]) {
$str = ltrim(substr($str, 1));
} else {
break;
}
}
if ('}' != $str[0]) {
throw new JsParserException("Unexpected token '".$str[0]."' expected }");
}
$str = ltrim(substr($str, 1));
return $ret;
}
}