2016-12-29 14:09:49 -06:00
|
|
|
<?php
|
2016-08-15 23:46:26 -05:00
|
|
|
|
2016-05-23 22:48:28 -05:00
|
|
|
namespace Amp;
|
2016-05-21 09:44:52 -05:00
|
|
|
|
2017-02-20 14:53:58 -06:00
|
|
|
use React\Promise\PromiseInterface as ReactPromise;
|
|
|
|
|
2016-06-01 12:18:11 -05:00
|
|
|
/**
|
2017-06-06 12:57:03 -05:00
|
|
|
* Creates a successful promise using the given value (which can be any value except an object implementing
|
|
|
|
* `Amp\Promise` or `React\Promise\PromiseInterface`).
|
2020-03-28 12:23:46 +01:00
|
|
|
*
|
|
|
|
* @template-covariant TValue
|
|
|
|
* @template-implements Promise<TValue>
|
2016-06-01 12:18:11 -05:00
|
|
|
*/
|
2018-06-18 20:00:01 +02:00
|
|
|
final class Success implements Promise
|
|
|
|
{
|
2016-08-17 22:25:54 -05:00
|
|
|
/** @var mixed */
|
2016-05-21 09:44:52 -05:00
|
|
|
private $value;
|
|
|
|
|
|
|
|
/**
|
2017-03-12 17:05:52 +01:00
|
|
|
* @param mixed $value Anything other than a Promise object.
|
2016-05-21 09:44:52 -05:00
|
|
|
*
|
2020-03-28 12:23:46 +01:00
|
|
|
* @psalm-param TValue $value
|
|
|
|
*
|
2016-11-14 13:59:21 -06:00
|
|
|
* @throws \Error If a promise is given as the value.
|
2016-05-21 09:44:52 -05:00
|
|
|
*/
|
2018-06-18 20:00:01 +02:00
|
|
|
public function __construct($value = null)
|
|
|
|
{
|
2017-02-20 14:53:58 -06:00
|
|
|
if ($value instanceof Promise || $value instanceof ReactPromise) {
|
2016-11-14 13:59:21 -06:00
|
|
|
throw new \Error("Cannot use a promise as success value");
|
2016-05-21 09:44:52 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
$this->value = $value;
|
|
|
|
}
|
|
|
|
|
2020-05-20 10:59:24 -05:00
|
|
|
/**
|
|
|
|
* Catches any destructor exception thrown and rethrows it to the event loop.
|
|
|
|
*/
|
|
|
|
public function __destruct()
|
|
|
|
{
|
|
|
|
try {
|
|
|
|
$this->value = null;
|
|
|
|
} catch (\Throwable $e) {
|
|
|
|
Loop::defer(static function () use ($e) {
|
|
|
|
throw $e;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-05-21 09:44:52 -05:00
|
|
|
/**
|
|
|
|
* {@inheritdoc}
|
|
|
|
*/
|
2018-06-18 20:00:01 +02:00
|
|
|
public function onResolve(callable $onResolved)
|
|
|
|
{
|
2016-05-21 09:44:52 -05:00
|
|
|
try {
|
2017-03-27 18:37:55 -05:00
|
|
|
$result = $onResolved(null, $this->value);
|
|
|
|
|
|
|
|
if ($result === null) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if ($result instanceof \Generator) {
|
|
|
|
$result = new Coroutine($result);
|
|
|
|
}
|
|
|
|
|
|
|
|
if ($result instanceof Promise || $result instanceof ReactPromise) {
|
|
|
|
Promise\rethrow($result);
|
|
|
|
}
|
2020-05-20 10:59:24 -05:00
|
|
|
} catch (\Throwable $e) {
|
|
|
|
Loop::defer(static function () use ($e) {
|
|
|
|
throw $e;
|
2017-03-10 15:32:58 -06:00
|
|
|
});
|
2016-05-21 09:44:52 -05:00
|
|
|
}
|
|
|
|
}
|
2016-05-22 13:43:37 -05:00
|
|
|
}
|