Skip to content

Commit

Permalink
Encoder: fixed encoding of control characters [Closes #72]
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes authored and dg committed Oct 4, 2024
1 parent 8a7df4e commit 3411aa8
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/Neon/Node/StringNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,14 +70,16 @@ function (array $m): string {
public function toString(): string
{
if (!str_contains($this->value, "\n")) {
return "'" . str_replace("'", "''", $this->value) . "'";
return preg_match('~[\x00-\x08\x0B-\x1F]~', $this->value)
? json_encode($this->value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
: "'" . str_replace("'", "''", $this->value) . "'";

} elseif (preg_match('~\n[\t ]+\'{3}~', $this->value)) {
$s = json_encode($this->value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} elseif (preg_match('~[\x00-\x08\x0B-\x1F]|\n[\t ]+\'{3}~', $this->value)) {
$s = substr(json_encode($this->value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 1, -1);
$s = preg_replace_callback(
'#[^\\\\]|\\\\(.)#s',
fn($m) => ['n' => "\n", 't' => "\t", '"' => '"'][$m[1] ?? ''] ?? $m[0],
substr($s, 1, -1),
$s,
);
$s = str_replace('"""', '""\"', $s);
$delim = '"""';
Expand Down
10 changes: 10 additions & 0 deletions tests/Neon/Encoder.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -170,3 +170,13 @@ Assert::exception(
Nette\Neon\Exception::class,
'INF and NAN cannot be encoded to NEON',
);

Assert::same(
'"special \u0000 chars"',
Neon::encode("special \x00 chars", true),
);

Assert::same(
"\"\"\"\n\tspecial\\r\n\tchars\n\"\"\"",
Neon::encode("special\r\nchars", true),
);

0 comments on commit 3411aa8

Please sign in to comment.