PocketMine-MP 5.21.2 git-b2aa6396c3cc2cafdd815eacc360e1ad89599899
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{
77 if(count($promises) === 0){
78 throw new \InvalidArgumentException("At least one promise must be provided");
79 }
81 $resolver = new PromiseResolver();
82 $values = [];
83 $toResolve = count($promises);
84 $continue = true;
85
86 foreach($promises as $key => $promise){
87 $promise->onCompletion(
88 function(mixed $value) use ($resolver, $key, $toResolve, &$values) : void{
89 $values[$key] = $value;
90
91 if(count($values) === $toResolve){
92 $resolver->resolve($values);
93 }
94 },
95 function() use ($resolver, &$continue) : void{
96 if($continue){
97 $continue = false;
98 $resolver->reject();
99 }
100 }
101 );
102
103 if(!$continue){
104 break;
105 }
106 }
107
108 return $resolver->getPromise();
109 }
110}
static all(array $promises)
Definition Promise.php:76
onCompletion(\Closure $onSuccess, \Closure $onFailure)
Definition Promise.php:44