TaskSystem/vendor/guzzlehttp/promises/src/FulfilledPromise.php

85 lines
1.9 KiB
PHP
Raw Normal View History

2023-07-15 10:16:32 +08:00
<?php
namespace GuzzleHttp\Promise;
/**
* A promise that has been fulfilled.
*
* Thenning off of this promise will invoke the onFulfilled callback
* immediately and ignore other callbacks.
*/
class FulfilledPromise implements PromiseInterface
{
private $value;
public function __construct($value)
{
if (is_object($value) && method_exists($value, 'then')) {
throw new \InvalidArgumentException(
'You cannot create a FulfilledPromise with a promise.'
);
}
$this->value = $value;
}
public function then(
callable $onFulfilled = null,
callable $onRejected = null
2023-07-18 11:17:17 +08:00
) {
2023-07-15 10:16:32 +08:00
// Return itself if there is no onFulfilled function.
if (!$onFulfilled) {
return $this;
}
$queue = Utils::queue();
$p = new Promise([$queue, 'run']);
$value = $this->value;
2023-07-18 11:17:17 +08:00
$queue->add(static function () use ($p, $value, $onFulfilled) {
2023-07-15 10:16:32 +08:00
if (Is::pending($p)) {
try {
$p->resolve($onFulfilled($value));
} catch (\Throwable $e) {
$p->reject($e);
2023-07-18 11:17:17 +08:00
} catch (\Exception $e) {
$p->reject($e);
2023-07-15 10:16:32 +08:00
}
}
});
return $p;
}
2023-07-18 11:17:17 +08:00
public function otherwise(callable $onRejected)
2023-07-15 10:16:32 +08:00
{
return $this->then(null, $onRejected);
}
2023-07-18 11:17:17 +08:00
public function wait($unwrap = true, $defaultDelivery = null)
2023-07-15 10:16:32 +08:00
{
return $unwrap ? $this->value : null;
}
2023-07-18 11:17:17 +08:00
public function getState()
2023-07-15 10:16:32 +08:00
{
return self::FULFILLED;
}
2023-07-18 11:17:17 +08:00
public function resolve($value)
2023-07-15 10:16:32 +08:00
{
if ($value !== $this->value) {
2023-07-18 11:17:17 +08:00
throw new \LogicException("Cannot resolve a fulfilled promise");
2023-07-15 10:16:32 +08:00
}
}
2023-07-18 11:17:17 +08:00
public function reject($reason)
2023-07-15 10:16:32 +08:00
{
2023-07-18 11:17:17 +08:00
throw new \LogicException("Cannot reject a fulfilled promise");
2023-07-15 10:16:32 +08:00
}
2023-07-18 11:17:17 +08:00
public function cancel()
2023-07-15 10:16:32 +08:00
{
// pass
}
}