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