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 f0c1fd9 commit 3b4af0c
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 @@ -80,16 +80,18 @@ function (array $m): string {
public function toString(): string
{
if (strpos($this->value, "\n") === false) {
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',
function ($m) {
return ['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 @@ -164,3 +164,13 @@ Assert::same(
'[]',
Neon::encode([], Neon::BLOCK)
);

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 3b4af0c

Please sign in to comment.