Skip to content

Commit 3411aa8

Browse files
ondrejmirtesdg
authored andcommitted
Encoder: fixed encoding of control characters [Closes #72]
1 parent 8a7df4e commit 3411aa8

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
@@ -70,14 +70,16 @@ function (array $m): string {
7070
public function toString(): string
7171
{
7272
if (!str_contains($this->value, "\n")) {
73-
return "'" . str_replace("'", "''", $this->value) . "'";
73+
return preg_match('~[\x00-\x08\x0B-\x1F]~', $this->value)
74+
? json_encode($this->value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
75+
: "'" . str_replace("'", "''", $this->value) . "'";
7476

75-
} elseif (preg_match('~\n[\t ]+\'{3}~', $this->value)) {
76-
$s = json_encode($this->value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
77+
} elseif (preg_match('~[\x00-\x08\x0B-\x1F]|\n[\t ]+\'{3}~', $this->value)) {
78+
$s = substr(json_encode($this->value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 1, -1);
7779
$s = preg_replace_callback(
7880
'#[^\\\\]|\\\\(.)#s',
7981
fn($m) => ['n' => "\n", 't' => "\t", '"' => '"'][$m[1] ?? ''] ?? $m[0],
80-
substr($s, 1, -1),
82+
$s,
8183
);
8284
$s = str_replace('"""', '""\"', $s);
8385
$delim = '"""';

tests/Neon/Encoder.phpt

+10
Original file line numberDiff line numberDiff line change
@@ -170,3 +170,13 @@ Assert::exception(
170170
Nette\Neon\Exception::class,
171171
'INF and NAN cannot be encoded to NEON',
172172
);
173+
174+
Assert::same(
175+
'"special \u0000 chars"',
176+
Neon::encode("special \x00 chars", true),
177+
);
178+
179+
Assert::same(
180+
"\"\"\"\n\tspecial\\r\n\tchars\n\"\"\"",
181+
Neon::encode("special\r\nchars", true),
182+
);

0 commit comments

Comments
 (0)