PocketMine-MP 5.21.2 git-a6534ecbbbcf369264567d27e5ed70f7f5be9816
Loading...
Searching...
No Matches
GameModeIdMap.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\java;
25
26use pocketmine\player\GameMode;
27use pocketmine\utils\SingletonTrait;
28use function array_key_exists;
29use function spl_object_id;
30
31final class GameModeIdMap{
32 use SingletonTrait;
33
38 private array $idToEnum = [];
39
44 private array $enumToId = [];
45
46 public function __construct(){
47 foreach(GameMode::cases() as $case){
48 $this->register(match($case){
49 GameMode::SURVIVAL => 0,
50 GameMode::CREATIVE => 1,
51 GameMode::ADVENTURE => 2,
52 GameMode::SPECTATOR => 3,
53 }, $case);
54 }
55 }
56
57 private function register(int $id, GameMode $type) : void{
58 $this->idToEnum[$id] = $type;
59 $this->enumToId[spl_object_id($type)] = $id;
60 }
61
62 public function fromId(int $id) : ?GameMode{
63 return $this->idToEnum[$id] ?? null;
64 }
65
66 public function toId(GameMode $type) : int{
67 $k = spl_object_id($type);
68 if(!array_key_exists($k, $this->enumToId)){
69 throw new \InvalidArgumentException("Game mode $type->name does not have a mapped ID"); //this should never happen
70 }
71 return $this->enumToId[$k];
72 }
73}