1
0
mirror of https://github.com/danog/amp.git synced 2024-12-13 18:07:30 +01:00
amp/lib/Deferred.php

78 lines
1.8 KiB
PHP
Raw Normal View History

<?php
2016-08-16 06:46:26 +02:00
2016-05-24 05:48:28 +02:00
namespace Amp;
2016-05-21 16:44:52 +02:00
/**
* Deferred is a container for a promise that is resolved using the resolve() and fail() methods of this object.
* The contained promise may be accessed using the promise() method. This object should not be part of a public
* API, but used internally to create and resolve a promise.
2020-04-04 16:35:52 +02:00
*
* @template TValue
*/
2018-06-18 20:00:01 +02:00
final class Deferred
{
2020-04-04 16:35:52 +02:00
/** @var Promise<TValue> Has public resolve and fail methods. */
2017-12-20 17:30:43 +01:00
private $resolver;
2020-04-04 16:35:52 +02:00
/** @var Promise<TValue> Hides placeholder methods */
private $promise;
2018-06-18 20:00:01 +02:00
public function __construct()
{
$this->resolver = new class implements Promise {
use Internal\Placeholder {
resolve as public;
fail as public;
isResolved as public;
2016-05-21 16:44:52 +02:00
}
};
2017-12-20 17:30:43 +01:00
$this->promise = new Internal\PrivatePromise($this->resolver);
}
2016-05-21 16:44:52 +02:00
/**
2020-04-04 16:35:52 +02:00
* @return Promise<TValue>
*/
2018-06-18 20:00:01 +02:00
public function promise(): Promise
{
return $this->promise;
}
2016-05-21 16:44:52 +02:00
/**
* @return bool True if the contained promise has been resolved.
*/
public function isResolved(): bool
{
2020-07-17 18:19:36 +02:00
/** @psalm-suppress UndefinedInterfaceMethod */
return $this->resolver->isResolved();
}
/**
* Fulfill the promise with the given value.
*
* @param mixed $value
*
2020-04-05 22:37:09 +02:00
* @psalm-param TValue|Promise<TValue> $value
2020-04-04 16:35:52 +02:00
*
* @return void
*/
2018-06-18 20:00:01 +02:00
public function resolve($value = null)
{
/** @psalm-suppress UndefinedInterfaceMethod */
2017-12-20 17:30:43 +01:00
$this->resolver->resolve($value);
}
2016-05-21 16:44:52 +02:00
/**
* Fails the promise the the given reason.
*
* @param \Throwable $reason
*
* @return void
*/
2018-06-18 20:00:01 +02:00
public function fail(\Throwable $reason)
{
/** @psalm-suppress UndefinedInterfaceMethod */
2017-12-20 17:30:43 +01:00
$this->resolver->fail($reason);
2016-05-21 16:44:52 +02:00
}
}