1: <?php
2:
3: 4: 5: 6:
7:
8: namespace Nette\Neon;
9:
10:
11: 12: 13: 14: 15:
16: class Encoder
17: {
18: const BLOCK = 1;
19:
20:
21: 22: 23: 24: 25: 26:
27: public function encode($var, $options = NULL)
28: {
29: if ($var instanceof \DateTime) {
30: return $var->format('Y-m-d H:i:s O');
31:
32: } elseif ($var instanceof Entity) {
33: return $this->encode($var->value) . '('
34: . (is_array($var->attributes) ? substr($this->encode($var->attributes), 1, -1) : '') . ')';
35: }
36:
37: if (is_object($var)) {
38: $obj = $var;
39: $var = array();
40: foreach ($obj as $k => $v) {
41: $var[$k] = $v;
42: }
43: }
44:
45: if (is_array($var)) {
46: $isList = !$var || array_keys($var) === range(0, count($var) - 1);
47: $s = '';
48: if ($options & self::BLOCK) {
49: if (count($var) === 0) {
50: return '[]';
51: }
52: foreach ($var as $k => $v) {
53: $v = $this->encode($v, self::BLOCK);
54: $s .= ($isList ? '-' : $this->encode($k) . ':')
55: . (strpos($v, "\n") === FALSE
56: ? ' ' . $v . "\n"
57: : "\n" . preg_replace('#^(?=.)#m', "\t", $v) . (substr($v, -2, 1) === "\n" ? '' : "\n"));
58: }
59: return $s;
60:
61: } else {
62: foreach ($var as $k => $v) {
63: $s .= ($isList ? '' : $this->encode($k) . ': ') . $this->encode($v) . ', ';
64: }
65: return ($isList ? '[' : '{') . substr($s, 0, -2) . ($isList ? ']' : '}');
66: }
67:
68: } elseif (is_string($var) && !is_numeric($var)
69: && !preg_match('~[\x00-\x1F]|^\d{4}|^(true|false|yes|no|on|off|null)\z~i', $var)
70: && preg_match('~^' . Decoder::$patterns[1] . '\z~x', $var)
71: ) {
72: return $var;
73:
74: } elseif (is_float($var)) {
75: $var = json_encode($var);
76: return strpos($var, '.') === FALSE ? $var . '.0' : $var;
77:
78: } else {
79: return json_encode($var, PHP_VERSION_ID >= 50400 ? JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES : 0);
80: }
81: }
82:
83: }
84: