From e9afc03613216aba60a800af02d15518b45fa362 Mon Sep 17 00:00:00 2001 From: Kurt Thiemann Date: Tue, 9 Jul 2024 13:03:23 +0200 Subject: [PATCH] correctly escape strings in SNBT instead of just using json_encode --- src/Tag/CompoundTag.php | 2 +- src/Tag/StringTag.php | 28 +++++++++++++++++++++++++++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/Tag/CompoundTag.php b/src/Tag/CompoundTag.php index b1a5471..ae5e778 100644 --- a/src/Tag/CompoundTag.php +++ b/src/Tag/CompoundTag.php @@ -421,7 +421,7 @@ public function toSNBT(): string { $data = []; foreach ($this->valueArray as $value) { - $data[] = json_encode($value->getName()) . ": " . $value->toSNBT(); + $data[] = StringTag::encodeSNBTString($value->getName()) . ": " . $value->toSNBT(); } return "{" . implode(", ", $data) . "}"; } diff --git a/src/Tag/StringTag.php b/src/Tag/StringTag.php index fbe5ccd..b3dd014 100644 --- a/src/Tag/StringTag.php +++ b/src/Tag/StringTag.php @@ -12,6 +12,32 @@ class StringTag extends Tag protected string $value = ""; + /** + * @param string $source + * @return string + */ + public static function encodeSNBTString(string $source): string + { + $quoteChar = '"'; + if (str_contains($source, '"') && !str_contains($source, "'")) { + $quoteChar = "'"; + } + + $result = ""; + for ($i = 0; $i < strlen($source); $i++) { + $char = $source[$i]; + if ($char === "\\") { + $result .= "\\\\"; + } else if ($char === $quoteChar) { + $result .= "\\" . $quoteChar; + } else { + $result .= $char; + } + } + + return $quoteChar . $result . $quoteChar; + } + /** * @return string */ @@ -100,6 +126,6 @@ public function equals(Tag $tag): bool */ public function toSNBT(): string { - return json_encode($this->value); + return static::encodeSNBTString($this->value); } }