PocketMine-MP 5.21.2 git-a6534ecbbbcf369264567d27e5ed70f7f5be9816
Loading...
Searching...
No Matches
Promise.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\promise;
25
26use function count;
27use function spl_object_id;
28
32final class Promise{
38 public function __construct(private PromiseSharedData $shared){}
39
44 public function onCompletion(\Closure $onSuccess, \Closure $onFailure) : void{
45 $state = $this->shared->state;
46 if($state === true){
47 $onSuccess($this->shared->result);
48 }elseif($state === false){
49 $onFailure();
50 }else{
51 $this->shared->onSuccess[spl_object_id($onSuccess)] = $onSuccess;
52 $this->shared->onFailure[spl_object_id($onFailure)] = $onFailure;
53 }
54 }
55
56 public function isResolved() : bool{
57 //TODO: perhaps this should return true when rejected? currently there's no way to tell if a promise was
58 //rejected or just hasn't been resolved yet
59 return $this->shared->state === true;
60 }
61
76 public static function all(array $promises) : Promise{
78 $resolver = new PromiseResolver();
79 if(count($promises) === 0){
80 $resolver->resolve([]);
81 return $resolver->getPromise();
82 }
83 $values = [];
84 $toResolve = count($promises);
85 $continue = true;
86
87 foreach($promises as $key => $promise){
88 $promise->onCompletion(
89 function(mixed $value) use ($resolver, $key, $toResolve, &$values) : void{
90 $values[$key] = $value;
91
92 if(count($values) === $toResolve){
93 $resolver->resolve($values);
94 }
95 },
96 function() use ($resolver, &$continue) : void{
97 if($continue){
98 $continue = false;
99 $resolver->reject();
100 }
101 }
102 );
103
104 if(!$continue){
105 break;
106 }
107 }
108
109 return $resolver->getPromise();
110 }
111}
static all(array $promises)
Definition Promise.php:76
onCompletion(\Closure $onSuccess, \Closure $onFailure)
Definition Promise.php:44