Skip to content

Commit bb88bf3

Browse files
ondrejmirtesdg
authored andcommitted
Encoder: fixed encoding of control characters [Closes #72]
1 parent fabfb9e commit bb88bf3

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

src/Neon/Node/StringNode.php

+6-4
Original file line numberDiff line numberDiff line change
@@ -80,16 +80,18 @@ function (array $m): string {
8080
public function toString(): string
8181
{
8282
if (strpos($this->value, "\n") === false) {
83-
return "'" . str_replace("'", "''", $this->value) . "'";
83+
return preg_match('~[\x00-\x08\x0B-\x1F]~', $this->value)
84+
? json_encode($this->value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
85+
: "'" . str_replace("'", "''", $this->value) . "'";
8486

85-
} elseif (preg_match('~\n[\t ]+\'{3}~', $this->value)) {
86-
$s = json_encode($this->value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
87+
} elseif (preg_match('~[\x00-\x08\x0B-\x1F]|\n[\t ]+\'{3}~', $this->value)) {
88+
$s = substr(json_encode($this->value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 1, -1);
8789
$s = preg_replace_callback(
8890
'#[^\\\\]|\\\\(.)#s',
8991
function ($m) {
9092
return ['n' => "\n", 't' => "\t", '"' => '"'][$m[1] ?? ''] ?? $m[0];
9193
},
92-
substr($s, 1, -1)
94+
$s
9395
);
9496
$s = str_replace('"""', '""\"', $s);
9597
$delim = '"""';

tests/Neon/Encoder.phpt

+10
Original file line numberDiff line numberDiff line change
@@ -164,3 +164,13 @@ Assert::same(
164164
'[]',
165165
Neon::encode([], Neon::BLOCK)
166166
);
167+
168+
Assert::same(
169+
'"special \u0000 chars"',
170+
Neon::encode("special \x00 chars", true)
171+
);
172+
173+
Assert::same(
174+
"\"\"\"\n\tspecial\\r\n\tchars\n\"\"\"",
175+
Neon::encode("special\r\nchars", true)
176+
);

0 commit comments

Comments
 (0)