PocketMine-MP 5.32.2 git-1ebd7d3960d713d56f77f610fe0c15cdee201069
Loading...
Searching...
No Matches
BlockObjectToStateSerializer.php
1<?php
2
3/*
4 *
5 * ____ _ _ __ __ _ __ __ ____
6 * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
7 * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
8 * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
9 * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
10 *
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * @author PocketMine Team
17 * @link http://www.pocketmine.net/
18 *
19 *
20 */
21
22declare(strict_types=1);
23
24namespace pocketmine\data\bedrock\block\convert;
25
32use function get_class;
33
42 private array $serializers = [];
43
48 private array $cache = [];
49
50 public function serialize(int $stateId) : BlockStateData{
51 //TODO: singleton usage not ideal
52 //TODO: we may want to deduplicate cache entries to avoid wasting memory
53 return $this->cache[$stateId] ??= $this->serializeBlock(RuntimeBlockStateRegistry::getInstance()->fromStateId($stateId));
54 }
55
56 public function isRegistered(Block $block) : bool{
57 return isset($this->serializers[$block->getTypeId()]);
58 }
59
65 public function map(Block $block, \Closure|Writer|BlockStateData $serializer) : void{
66 if(isset($this->serializers[$block->getTypeId()])){
67 throw new \InvalidArgumentException("Block type ID " . $block->getTypeId() . " (" . $block->getName() . ") already has a serializer registered");
68 }
69 //writer accepted for convenience only
70 $this->serializers[$block->getTypeId()] = $serializer instanceof Writer ? $serializer->getBlockStateData() : $serializer;
71 }
72
79 public function serializeBlock(Block $blockState) : BlockStateData{
80 $typeId = $blockState->getTypeId();
81
82 $locatedSerializer = $this->serializers[$typeId] ?? null;
83 if($locatedSerializer === null){
84 throw new BlockStateSerializeException("No serializer registered for " . get_class($blockState) . " with type ID $typeId");
85 }
86
87 if($locatedSerializer instanceof BlockStateData){ //static data, not dependent on state
88 return $locatedSerializer;
89 }
90
99 $result = $locatedSerializer($blockState);
100
101 return $result instanceof Writer ? $result->getBlockStateData() : $result;
102 }
103}
map(Block $block, \Closure|Writer|BlockStateData $serializer)