PocketMine-MP 5.23.3 git-f7687af337d001ddbcc47b8e773f014a33faa662
Loading...
Searching...
No Matches
StringToTParser.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\utils;
25
26use function array_keys;
27use function str_replace;
28use function strtolower;
29use function trim;
30
39abstract class StringToTParser{
40
45 private array $callbackMap = [];
46
48 public function register(string $alias, \Closure $callback) : void{
49 $key = $this->reprocess($alias);
50 if(isset($this->callbackMap[$key])){
51 throw new \InvalidArgumentException("Alias \"$key\" is already registered");
52 }
53 $this->callbackMap[$key] = $callback;
54 }
55
57 public function override(string $alias, \Closure $callback) : void{
58 $this->callbackMap[$this->reprocess($alias)] = $callback;
59 }
60
64 public function registerAlias(string $existing, string $alias) : void{
65 $existingKey = $this->reprocess($existing);
66 if(!isset($this->callbackMap[$existingKey])){
67 throw new \InvalidArgumentException("Cannot register new alias for unknown existing alias \"$existing\"");
68 }
69 $newKey = $this->reprocess($alias);
70 if(isset($this->callbackMap[$newKey])){
71 throw new \InvalidArgumentException("Alias \"$newKey\" is already registered");
72 }
73 $this->callbackMap[$newKey] = $this->callbackMap[$existingKey];
74 }
75
80 public function parse(string $input){
81 $key = $this->reprocess($input);
82 if(isset($this->callbackMap[$key])){
83 return ($this->callbackMap[$key])($input);
84 }
85
86 return null;
87 }
88
89 protected function reprocess(string $input) : string{
90 return strtolower(str_replace([" ", "minecraft:"], ["_", ""], trim($input)));
91 }
92
94 public function getKnownAliases() : array{
95 return array_keys($this->callbackMap);
96 }
97}
registerAlias(string $existing, string $alias)