2016-12-29 21:09:49 +01:00
|
|
|
<?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
|
|
|
|
2016-06-01 19:18:11 +02:00
|
|
|
/**
|
2017-06-06 19:57:03 +02:00
|
|
|
* Creates a successful promise using the given value (which can be any value except an object implementing
|
2020-10-30 16:17:52 +01:00
|
|
|
* `Amp\Promise`).
|
2020-03-28 12:23:46 +01:00
|
|
|
*
|
|
|
|
* @template-covariant TValue
|
|
|
|
* @template-implements Promise<TValue>
|
2016-06-01 19:18:11 +02:00
|
|
|
*/
|
2018-06-18 20:00:01 +02:00
|
|
|
final class Success implements Promise
|
|
|
|
{
|
2020-09-24 18:52:22 +02:00
|
|
|
private mixed $value;
|
2016-05-21 16:44:52 +02:00
|
|
|
|
|
|
|
/**
|
2017-03-12 17:05:52 +01:00
|
|
|
* @param mixed $value Anything other than a Promise object.
|
2016-05-21 16:44:52 +02:00
|
|
|
*
|
2020-03-28 12:23:46 +01:00
|
|
|
* @psalm-param TValue $value
|
|
|
|
*
|
2016-11-14 20:59:21 +01:00
|
|
|
* @throws \Error If a promise is given as the value.
|
2016-05-21 16:44:52 +02:00
|
|
|
*/
|
2020-09-24 18:52:22 +02:00
|
|
|
public function __construct(mixed $value = null)
|
2018-06-18 20:00:01 +02:00
|
|
|
{
|
2020-10-30 16:17:52 +01:00
|
|
|
if ($value instanceof Promise) {
|
2016-11-14 20:59:21 +01:00
|
|
|
throw new \Error("Cannot use a promise as success value");
|
2016-05-21 16:44:52 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
$this->value = $value;
|
|
|
|
}
|
|
|
|
|
2020-05-20 17:59:24 +02:00
|
|
|
/**
|
|
|
|
* Catches any destructor exception thrown and rethrows it to the event loop.
|
|
|
|
*/
|
|
|
|
public function __destruct()
|
|
|
|
{
|
|
|
|
try {
|
|
|
|
$this->value = null;
|
|
|
|
} catch (\Throwable $e) {
|
2020-11-01 18:19:17 +01:00
|
|
|
Loop::defer(static function () use ($e): void {
|
2020-05-20 17:59:24 +02:00
|
|
|
throw $e;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-05-21 16:44:52 +02:00
|
|
|
/**
|
|
|
|
* {@inheritdoc}
|
|
|
|
*/
|
2020-09-24 18:52:22 +02:00
|
|
|
public function onResolve(callable $onResolved): void
|
2018-06-18 20:00:01 +02:00
|
|
|
{
|
2020-11-01 18:19:17 +01:00
|
|
|
Loop::defer(fn() => $onResolved(null, $this->value));
|
2016-05-21 16:44:52 +02:00
|
|
|
}
|
2016-05-22 20:43:37 +02:00
|
|
|
}
|