PocketMine-MP 5.23.3 git-f7687af337d001ddbcc47b8e773f014a33faa662
Loading...
Searching...
No Matches
IntSaveIdMapTrait.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;
25
26use function array_key_exists;
27use function spl_object_id;
28
32trait IntSaveIdMapTrait{
33
38 private array $idToEnum = [];
39
44 private array $enumToId = [];
45
49 protected function getRuntimeId(object $enum) : int{
50 //this is fine for enums and non-cloning object registries
51 return spl_object_id($enum);
52 }
53
57 public function register(int $saveId, object $enum) : void{
58 $this->idToEnum[$saveId] = $enum;
59 $this->enumToId[$this->getRuntimeId($enum)] = $saveId;
60 }
61
65 public function fromId(int $id) : ?object{
66 //we might not have all the effect IDs registered
67 return $this->idToEnum[$id] ?? null;
68 }
69
73 public function toId(object $enum) : int{
74 $runtimeId = $this->getRuntimeId($enum);
75 if(!array_key_exists($runtimeId, $this->enumToId)){
76 //this should never happen, so we treat it as an exceptional condition
77 throw new \InvalidArgumentException("Object does not have a mapped save ID");
78 }
79 return $this->enumToId[$runtimeId];
80 }
81}