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