Skip to content

Commit

Permalink
correctly escape strings in SNBT instead of just using json_encode
Browse files Browse the repository at this point in the history
  • Loading branch information
KurtThiemann committed Jul 9, 2024
1 parent 255c5ad commit e9afc03
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/Tag/CompoundTag.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) . "}";
}
Expand Down
28 changes: 27 additions & 1 deletion src/Tag/StringTag.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand Down Expand Up @@ -100,6 +126,6 @@ public function equals(Tag $tag): bool
*/
public function toSNBT(): string
{
return json_encode($this->value);
return static::encodeSNBTString($this->value);
}
}

0 comments on commit e9afc03

Please sign in to comment.