22declare(strict_types=1);
24namespace pocketmine\data\bedrock\item;
35use
function get_class;
45 private array $itemSerializers = [];
51 private array $blockItemSerializers = [];
53 public function __construct(
56 $this->registerSpecialBlockSerializers();
65 public function map(
Item $item, \Closure $serializer) : void{
66 $index = $item->getTypeId();
67 if(isset($this->itemSerializers[$index])){
68 throw new \InvalidArgumentException(
"Item type ID " . $index .
" already has a serializer registered");
70 $this->itemSerializers[$index] = $serializer;
79 $index = $block->getTypeId();
80 if(isset($this->blockItemSerializers[$index])){
81 throw new \InvalidArgumentException(
"Block type ID " . $index .
" already has a serializer registered");
83 $this->blockItemSerializers[$index] = $serializer;
94 throw new \InvalidArgumentException(
"Cannot serialize a null itemstack");
97 $data = $this->serializeBlockItem($item->
getBlock());
99 $index = $item->getTypeId();
101 $locatedSerializer = $this->itemSerializers[$index] ??
null;
102 if($locatedSerializer ===
null){
103 throw new ItemTypeSerializeException(
"No serializer registered for " . get_class($item) .
" ($index) " . $item->
getName());
114 $serializer = $locatedSerializer;
117 $data = $serializer($item);
122 $extraTag = $data->getTag();
123 if($extraTag !==
null){
124 $resultTag = $resultTag->merge($extraTag);
126 $data =
new Data($data->getName(), $data->getMeta(), $data->getBlock(), $resultTag);
132 public function serializeStack(Item $item, ?
int $slot =
null) : SavedItemStackData{
133 return new SavedItemStackData(
134 $this->serializeType($item),
149 private function serializeBlockItem(Block $block) : Data{
150 $index = $block->getTypeId();
152 $locatedSerializer = $this->blockItemSerializers[$index] ??
null;
153 if($locatedSerializer !==
null){
161 $serializer = $locatedSerializer;
162 $data = $serializer($block);
164 $data = $this->standardBlock($block);
173 private function standardBlock(Block $block) : Data{
175 $blockStateData = $this->blockStateSerializer->serialize($block->getStateId());
176 }
catch(BlockStateSerializeException $e){
177 throw new ItemTypeSerializeException($e->getMessage(), 0, $e);
181 $itemNameId = BlockItemIdMap::getInstance()->lookupItemId($blockStateData->getName()) ?? $blockStateData->getName();
183 return new Data($itemNameId, 0, $blockStateData);
186 private function registerSpecialBlockSerializers() : void{
189 $this->map(Items::BAMBOO(), fn() => $this->standardBlock(Blocks::BAMBOO()));
190 $this->map(Items::CORAL_FAN(), fn(CoralFan $item) => $this->standardBlock($item->getBlock()));
mapBlock(Block $block, \Closure $serializer)
map(Item $item, \Closure $serializer)
serializeType(Item $item)
getBlock(?int $clickedFace=null)