Make SignText immutable

This commit is contained in:
Dylan K. Taylor 2020-06-29 20:18:10 +01:00
parent 42f543b405
commit e61a08a56b
2 changed files with 20 additions and 39 deletions

View File

@ -62,13 +62,14 @@ class Sign extends Spawnable{
if($nbt->hasTag(self::TAG_TEXT_BLOB, StringTag::class)){ //MCPE 1.2 save format
$this->text = SignText::fromBlob(mb_scrub($nbt->getString(self::TAG_TEXT_BLOB), 'UTF-8'));
}else{
$this->text = new SignText();
$text = [];
for($i = 0; $i < SignText::LINE_COUNT; ++$i){
$textKey = sprintf(self::TAG_TEXT_LINE, $i + 1);
if($nbt->hasTag($textKey, StringTag::class)){
$this->text->setLine($i, mb_scrub($nbt->getString($textKey), 'UTF-8'));
$text[$i] = mb_scrub($nbt->getString($textKey), 'UTF-8');
}
}
$this->text = new SignText($text);
}
}

View File

@ -39,13 +39,27 @@ class SignText{
private $lines;
/**
* @param string[] $lines
* @throws \InvalidArgumentException
* @param string[]|null $lines index-sensitive; omitting an index will leave it unchanged
*
* @throws \InvalidArgumentException if the array size is greater than 4
* @throws \InvalidArgumentException if invalid keys (out of bounds or string) are found in the array
* @throws \InvalidArgumentException if any line is not valid UTF-8 or contains a newline
*/
public function __construct(?array $lines = null){
$this->lines = array_fill(0, self::LINE_COUNT, "");
if($lines !== null){
$this->setLines($lines);
if(count($lines) > self::LINE_COUNT){
throw new \InvalidArgumentException("Expected at most 4 lines, got " . count($lines));
}
foreach($lines as $k => $line){
$this->checkLineIndex($k);
Utils::checkUTF8($line);
if(strpos($line, "\n") !== false){
throw new \InvalidArgumentException("Line must not contain newlines");
}
//TODO: add length checks
$this->lines[$k] = $line;
}
}
}
@ -68,24 +82,6 @@ class SignText{
return $this->lines;
}
/**
* Sets the sign text.
*
* @param string[] $lines index-sensitive; omitting an index will leave it unchanged
*
* @throws \InvalidArgumentException if the array size is greater than 4
* @throws \InvalidArgumentException if invalid keys (out of bounds or string) are found in the array
*/
public function setLines(array $lines) : void{
if(count($lines) > self::LINE_COUNT){
throw new \InvalidArgumentException("Expected at most 4 lines, got " . count($lines));
}
foreach($lines as $k => $line){
$this->checkLineIndex($k);
$this->setLine($k, $line);
}
}
/**
* @param int|string $index
*/
@ -107,20 +103,4 @@ class SignText{
$this->checkLineIndex($index);
return $this->lines[$index];
}
/**
* Sets the line at the given offset.
*
* @throws \InvalidArgumentException if the text is not valid UTF-8
* @throws \InvalidArgumentException if the text contains a newline
*/
public function setLine(int $index, string $line) : void{
$this->checkLineIndex($index);
Utils::checkUTF8($line);
if(strpos($line, "\n") !== false){
throw new \InvalidArgumentException("Line must not contain newlines");
}
//TODO: add length checks
$this->lines[$index] = $line;
}
}