PocketMine-MP 5.15.1 git-5ef247620a7c6301a849b54e5ef1009217729fc8
CompressBatchPromise.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\network\mcpe\compression;
25
26use function array_push;
27
33 private array $callbacks = [];
34
35 private ?string $result = null;
36
37 private bool $cancelled = false;
38
42 public function onResolve(\Closure ...$callbacks) : void{
43 $this->checkCancelled();
44 if($this->result !== null){
45 foreach($callbacks as $callback){
46 $callback($this);
47 }
48 }else{
49 array_push($this->callbacks, ...$callbacks);
50 }
51 }
52
53 public function resolve(string $result) : void{
54 if(!$this->cancelled){
55 if($this->result !== null){
56 throw new \LogicException("Cannot resolve promise more than once");
57 }
58 $this->result = $result;
59 foreach($this->callbacks as $callback){
60 $callback($this);
61 }
62 $this->callbacks = [];
63 }
64 }
65
70 public function getResolveCallbacks() : array{
71 return $this->callbacks;
72 }
73
74 public function getResult() : string{
75 $this->checkCancelled();
76 if($this->result === null){
77 throw new \LogicException("Promise has not yet been resolved");
78 }
79 return $this->result;
80 }
81
82 public function hasResult() : bool{
83 return $this->result !== null;
84 }
85
86 public function isCancelled() : bool{
87 return $this->cancelled;
88 }
89
90 public function cancel() : void{
91 if($this->hasResult()){
92 throw new \LogicException("Cannot cancel a resolved promise");
93 }
94 $this->cancelled = true;
95 }
96
97 private function checkCancelled() : void{
98 if($this->cancelled){
99 throw new \InvalidArgumentException("Promise has been cancelled");
100 }
101 }
102}