| 1 |
<?php |
| 2 |
|
| 3 |
namespace Amp; |
| 4 |
|
| 5 |
/** |
| 6 |
* Deferred is a container for a promise that is resolved using the resolve() and fail() methods of this object. |
| 7 |
* The contained promise may be accessed using the promise() method. This object should not be part of a public |
| 8 |
* API, but used internally to create and resolve a promise. |
| 9 |
* |
| 10 |
* @template TValue |
| 11 |
*/ |
| 12 |
final class Deferred |
| 13 |
{ |
| 14 |
/** @var Promise<TValue> Has public resolve and fail methods. */ |
| 15 |
private $resolver; |
| 16 |
|
| 17 |
/** @var Promise<TValue> Hides placeholder methods */ |
| 18 |
private $promise; |
| 19 |
|
| 20 |
public function __construct() |
| 21 |
{ |
| 22 |
$this->resolver = new class implements Promise { |
| 23 |
use Internal\Placeholder { |
| 24 |
resolve as public; |
| 25 |
fail as public; |
| 26 |
} |
| 27 |
}; |
| 28 |
|
| 29 |
$this->promise = new Internal\PrivatePromise($this->resolver); |
| 30 |
} |
| 31 |
|
| 32 |
/** |
| 33 |
* @return Promise<TValue> |
| 34 |
*/ |
| 35 |
public function promise(): Promise |
| 36 |
{ |
| 37 |
return $this->promise; |
| 38 |
} |
| 39 |
|
| 40 |
/** |
| 41 |
* Fulfill the promise with the given value. |
| 42 |
* |
| 43 |
* @param mixed $value |
| 44 |
* |
| 45 |
* @psalm-param TValue|Promise<TValue> $value |
| 46 |
* |
| 47 |
* @return void |
| 48 |
*/ |
| 49 |
public function resolve($value = null) |
| 50 |
{ |
| 51 |
/** @psalm-suppress UndefinedInterfaceMethod */ |
| 52 |
$this->resolver->resolve($value); |
| 53 |
} |
| 54 |
|
| 55 |
/** |
| 56 |
* Fails the promise the the given reason. |
| 57 |
* |
| 58 |
* @param \Throwable $reason |
| 59 |
* |
| 60 |
* @return void |
| 61 |
*/ |
| 62 |
public function fail(\Throwable $reason) |
| 63 |
{ |
| 64 |
/** @psalm-suppress UndefinedInterfaceMethod */ |
| 65 |
$this->resolver->fail($reason); |
| 66 |
} |
| 67 |
} |
| 68 |
|