1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10:
11:
12: namespace Nette;
13:
14: use Nette;
15:
16:
17:
18: 19: 20: 21: 22:
23: class Neon extends Object
24: {
25: const BLOCK = 1;
26:
27:
28: private static $patterns = array(
29: '\'[^\'\n]*\'|"(?:\\\\.|[^"\\\\\n])*"', 30: '@[a-zA-Z_0-9\\\\]+', 31: '[:-](?=\s|$)|[,=[\]{}()]', 32: '?:#.*', 33: '\n[\t ]*', 34: '[^#"\',:=@[\]{}()<>\x00-\x20!`](?:[^#,:=\]})>\x00-\x1F]+|:(?!\s|$)|(?<!\s)#)*(?<!\s)', 35: '?:[\t ]+', 36: );
37:
38:
39: private static $tokenizer;
40:
41: private static $brackets = array(
42: '[' => ']',
43: '{' => '}',
44: '(' => ')',
45: );
46:
47:
48: private $n = 0;
49:
50:
51: private $indentTabs;
52:
53:
54: 55: 56: 57: 58: 59:
60: public static function encode($var, $options = NULL)
61: {
62: if ($var instanceof \DateTime) {
63: return $var->format('Y-m-d H:i:s O');
64: }
65: if (is_object($var)) {
66: $obj = $var; $var = array();
67: foreach ($obj as $k => $v) {
68: $var[$k] = $v;
69: }
70: }
71: if (is_array($var)) {
72: $isArray = array_keys($var) === range(0, count($var) - 1);
73: $s = '';
74: if ($options & self::BLOCK) {
75: foreach ($var as $k => $v) {
76: $v = self::encode($v, self::BLOCK);
77: $s .= ($isArray ? '-' : self::encode($k) . ':')
78: . (strpos($v, "\n") === FALSE ? ' ' . $v : "\n\t" . str_replace("\n", "\n\t", $v))
79: . "\n";
80: continue;
81: }
82: return $s;
83:
84: } else {
85: foreach ($var as $k => $v) {
86: $s .= ($isArray ? '' : self::encode($k) . ': ') . self::encode($v) . ', ';
87: }
88: return ($isArray ? '[' : '{') . substr($s, 0, -2) . ($isArray ? ']' : '}');
89: }
90:
91: } elseif (is_string($var) && !is_numeric($var)
92: && !preg_match('~[\x00-\x1F]|^\d{4}|^(true|false|yes|no|on|off|null)$~i', $var)
93: && preg_match('~^' . self::$patterns[5] . '$~', $var)
94: ) {
95: return $var;
96:
97: } else {
98: return json_encode($var);
99: }
100: }
101:
102:
103:
104: 105: 106: 107: 108:
109: public static function decode($input)
110: {
111: if (!is_string($input)) {
112: throw new \InvalidArgumentException("Argument must be a string, " . gettype($input) . " given.");
113: }
114: if (!self::$tokenizer) {
115: self::$tokenizer = new Tokenizer(self::$patterns, 'mi');
116: }
117:
118: $input = str_replace("\r", '', $input);
119: self::$tokenizer->tokenize($input);
120:
121: $parser = new self;
122: $res = $parser->parse(0);
123:
124: while (isset(self::$tokenizer->tokens[$parser->n])) {
125: if (self::$tokenizer->tokens[$parser->n][0] === "\n") {
126: $parser->n++;
127: } else {
128: $parser->error();
129: }
130: }
131: return $res;
132: }
133:
134:
135:
136: 137: 138: 139: 140:
141: private function parse($indent = NULL, $result = NULL)
142: {
143: $inlineParser = $indent === NULL;
144: $value = $key = $object = NULL;
145: $hasValue = $hasKey = FALSE;
146: $tokens = self::$tokenizer->tokens;
147: $n = & $this->n;
148: $count = count($tokens);
149:
150: for (; $n < $count; $n++) {
151: $t = $tokens[$n];
152:
153: if ($t === ',') { 154: if (!$hasValue || !$inlineParser) {
155: $this->error();
156: }
157: if ($hasKey) $result[$key] = $value; else $result[] = $value;
158: $hasKey = $hasValue = FALSE;
159:
160: } elseif ($t === ':' || $t === '=') { 161: if ($hasKey || !$hasValue) {
162: $this->error();
163: }
164: if (is_array($value) || (is_object($value) && !method_exists($value, '__toString'))) {
165: $this->error('Unacceptable key');
166: } else {
167: $key = (string) $value;
168: }
169: $hasKey = TRUE;
170: $hasValue = FALSE;
171:
172: } elseif ($t === '-') { 173: if ($hasKey || $hasValue || $inlineParser) {
174: $this->error();
175: }
176: $key = NULL;
177: $hasKey = TRUE;
178:
179: } elseif (isset(self::$brackets[$t])) { 180: if ($hasValue) {
181: $this->error();
182: }
183: $endBracket = self::$brackets[$tokens[$n++]];
184: $hasValue = TRUE;
185: $value = $this->parse(NULL, array());
186: if (!isset($tokens[$n]) || $tokens[$n] !== $endBracket) { 187: $this->error();
188: }
189:
190: } elseif ($t === ']' || $t === '}' || $t === ')') { 191: if (!$inlineParser) {
192: $this->error();
193: }
194: break;
195:
196: } elseif ($t[0] === '@') { 197: $object = $t; 198:
199: } elseif ($t[0] === "\n") { 200: if ($inlineParser) {
201: if ($hasValue) {
202: if ($hasKey) $result[$key] = $value; else $result[] = $value;
203: $hasKey = $hasValue = FALSE;
204: }
205:
206: } else {
207: while (isset($tokens[$n+1]) && $tokens[$n+1][0] === "\n") $n++; 208: if (!isset($tokens[$n+1])) break;
209:
210: $newIndent = strlen($tokens[$n]) - 1;
211: if ($indent === NULL) { 212: $indent = $newIndent;
213: }
214: if ($newIndent) {
215: if ($this->indentTabs === NULL) {
216: $this->indentTabs = $tokens[$n][1] === "\t";
217: }
218: if (strpos($tokens[$n], $this->indentTabs ? ' ' : "\t")) {
219: $this->error('Either tabs or spaces may be used as indenting chars, but not both.');
220: }
221: }
222:
223: if ($newIndent > $indent) { 224: if ($hasValue || !$hasKey) {
225: $n++;
226: $this->error('Unexpected indentation.');
227: } elseif ($key === NULL) {
228: $result[] = $this->parse($newIndent);
229: } else {
230: $result[$key] = $this->parse($newIndent);
231: }
232: $newIndent = isset($tokens[$n]) ? strlen($tokens[$n]) - 1 : 0;
233: $hasKey = FALSE;
234:
235: } else {
236: if ($hasValue && !$hasKey) { 237: break;
238:
239: } elseif ($hasKey) {
240: $value = $hasValue ? $value : NULL;
241: if ($key === NULL) $result[] = $value; else $result[$key] = $value;
242: $hasKey = $hasValue = FALSE;
243: }
244: }
245:
246: if ($newIndent < $indent) { 247: return $result; 248: }
249: }
250:
251: } else { 252: if ($hasValue) {
253: $this->error();
254: }
255: static $consts = array(
256: 'true' => TRUE, 'True' => TRUE, 'TRUE' => TRUE, 'yes' => TRUE, 'Yes' => TRUE, 'YES' => TRUE, 'on' => TRUE, 'On' => TRUE, 'ON' => TRUE,
257: 'false' => FALSE, 'False' => FALSE, 'FALSE' => FALSE, 'no' => FALSE, 'No' => FALSE, 'NO' => FALSE, 'off' => FALSE, 'Off' => FALSE, 'OFF' => FALSE,
258: );
259: if ($t[0] === '"') {
260: $value = preg_replace_callback('#\\\\(?:u[0-9a-f]{4}|x[0-9a-f]{2}|.)#i', array($this, 'cbString'), substr($t, 1, -1));
261: } elseif ($t[0] === "'") {
262: $value = substr($t, 1, -1);
263: } elseif (isset($consts[$t])) {
264: $value = $consts[$t];
265: } elseif ($t === 'null' || $t === 'Null' || $t === 'NULL') {
266: $value = NULL;
267: } elseif (is_numeric($t)) {
268: $value = $t * 1;
269: } elseif (preg_match('#\d\d\d\d-\d\d?-\d\d?(?:(?:[Tt]| +)\d\d?:\d\d:\d\d(?:\.\d*)? *(?:Z|[-+]\d\d?(?::\d\d)?)?)?$#A', $t)) {
270: $value = new DateTime($t);
271: } else { 272: $value = $t;
273: }
274: $hasValue = TRUE;
275: }
276: }
277:
278: if ($inlineParser) {
279: if ($hasValue) {
280: if ($hasKey) $result[$key] = $value; else $result[] = $value;
281: } elseif ($hasKey) {
282: $this->error();
283: }
284: } else {
285: if ($hasValue && !$hasKey) { 286: if ($result === NULL) {
287: $result = $value; 288: } else {
289: $this->error();
290: }
291: } elseif ($hasKey) {
292: $value = $hasValue ? $value : NULL;
293: if ($key === NULL) $result[] = $value; else $result[$key] = $value;
294: }
295: }
296: return $result;
297: }
298:
299:
300:
301: private function cbString($m)
302: {
303: static $mapping = array('t' => "\t", 'n' => "\n", '"' => '"', '\\' => '\\', '/' => '/', '_' => "\xc2\xa0");
304: $sq = $m[0];
305: if (isset($mapping[$sq[1]])) {
306: return $mapping[$sq[1]];
307: } elseif ($sq[1] === 'u' && strlen($sq) === 6) {
308: return String::chr(hexdec(substr($sq, 2)));
309: } elseif ($sq[1] === 'x' && strlen($sq) === 4) {
310: return chr(hexdec(substr($sq, 2)));
311: } else {
312: $this->error("Invalid escaping sequence $sq");
313: }
314: }
315:
316:
317:
318: private function error($message = "Unexpected '%s'")
319: {
320: list(, $line, $col) = self::$tokenizer->getOffset($this->n);
321: $token = isset(self::$tokenizer->tokens[$this->n])
322: ? str_replace("\n", '<new line>', String::truncate(self::$tokenizer->tokens[$this->n], 40))
323: : 'end';
324: throw new NeonException(str_replace('%s', $token, $message) . " on line $line, column $col.");
325: }
326:
327: }
328:
329:
330:
331: 332: 333:
334: class NeonException extends \Exception
335: {
336: }
337: