Added item stack serialize/deserialize methods

This commit is contained in:
Dylan K. Taylor
2022-06-26 17:02:55 +01:00
parent 3d61345543
commit bc5a600d59
5 changed files with 38 additions and 28 deletions

View File

@ -64,7 +64,7 @@ final class ItemDeserializer{
/**
* @throws ItemTypeDeserializeException
*/
public function deserialize(Data $data) : Item{
public function deserializeType(Data $data) : Item{
if(($blockData = $data->getBlock()) !== null){
//TODO: this is rough duct tape; we need a better way to deal with this
try{
@ -84,6 +84,22 @@ final class ItemDeserializer{
return ($this->deserializers[$id])($data);
}
/**
* @throws ItemTypeDeserializeException
*/
public function deserializeStack(SavedItemStackData $data) : Item{
$itemStack = $this->deserializeType($data->getTypeData());
$itemStack->setCount($data->getCount());
if(($tagTag = $data->getTypeData()->getTag()) !== null){
$itemStack->setNamedTag(clone $tagTag);
}
//TODO: canDestroy, canPlaceOn, wasPickedUp are currently unused
return $itemStack;
}
private function registerDeserializers() : void{
$this->map(Ids::ACACIA_BOAT, fn() => Items::ACACIA_BOAT());
$this->map(Ids::ACACIA_DOOR, fn() => Blocks::ACACIA_DOOR()->asItem());

View File

@ -102,7 +102,7 @@ final class ItemSerializer{
*
* @throws ItemTypeSerializeException
*/
public function serialize(Item $item) : Data{
public function serializeType(Item $item) : Data{
if($item->isNull()){
throw new \InvalidArgumentException("Cannot serialize a null itemstack");
}
@ -128,7 +128,7 @@ final class ItemSerializer{
}
if($locatedSerializer === null){
throw new ItemTypeSerializeException("No serializer registered for " . get_class($item) . " " . $item->getName());
throw new ItemTypeSerializeException("No serializer registered for " . get_class($item) . " ($index) " . $item->getName());
}
/**
@ -153,6 +153,17 @@ final class ItemSerializer{
return $data;
}
public function serializeStack(Item $item, ?int $slot = null) : SavedItemStackData{
return new SavedItemStackData(
$this->serializeType($item),
$item->getCount(),
$slot,
null,
[], //we currently represent canDestroy and canPlaceOn via NBT, like PC
[]
);
}
/**
* @phpstan-template TBlockType of Block
* @phpstan-param TBlockType $block