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

96 lines
2.2 KiB
PHP
Raw Normal View History

2023-07-15 10:16:32 +08:00
<?php
2023-08-09 14:43:30 +08:00
declare(strict_types=1);
2023-07-15 10:16:32 +08:00
namespace GuzzleHttp\Promise;
/**
* A promise that has been rejected.
*
* Thenning off of this promise will invoke the onRejected callback
* immediately and ignore other callbacks.
2023-08-09 14:43:30 +08:00
*
* @final
2023-07-15 10:16:32 +08:00
*/
class RejectedPromise implements PromiseInterface
{
private $reason;
2023-08-09 14:43:30 +08:00
/**
* @param mixed $reason
*/
2023-07-15 10:16:32 +08:00
public function __construct($reason)
{
if (is_object($reason) && method_exists($reason, 'then')) {
throw new \InvalidArgumentException(
'You cannot create a RejectedPromise with a promise.'
);
}
$this->reason = $reason;
}
public function then(
callable $onFulfilled = null,
callable $onRejected = null
2023-08-09 14:43:30 +08:00
): PromiseInterface {
2023-07-15 10:16:32 +08:00
// If there's no onRejected callback then just return self.
if (!$onRejected) {
return $this;
}
$queue = Utils::queue();
$reason = $this->reason;
$p = new Promise([$queue, 'run']);
2023-08-09 14:43:30 +08:00
$queue->add(static function () use ($p, $reason, $onRejected): void {
2023-07-15 10:16:32 +08:00
if (Is::pending($p)) {
try {
// Return a resolved promise if onRejected does not throw.
$p->resolve($onRejected($reason));
} catch (\Throwable $e) {
// onRejected threw, so return a rejected promise.
$p->reject($e);
}
}
});
return $p;
}
2023-08-09 14:43:30 +08:00
public function otherwise(callable $onRejected): PromiseInterface
2023-07-15 10:16:32 +08:00
{
return $this->then(null, $onRejected);
}
2023-08-09 14:43:30 +08:00
public function wait(bool $unwrap = true)
2023-07-15 10:16:32 +08:00
{
if ($unwrap) {
throw Create::exceptionFor($this->reason);
}
return null;
}
2023-08-09 14:43:30 +08:00
public function getState(): string
2023-07-15 10:16:32 +08:00
{
return self::REJECTED;
}
2023-08-09 14:43:30 +08:00
public function resolve($value): void
2023-07-15 10:16:32 +08:00
{
2023-08-09 14:43:30 +08:00
throw new \LogicException('Cannot resolve a rejected promise');
2023-07-15 10:16:32 +08:00
}
2023-08-09 14:43:30 +08:00
public function reject($reason): void
2023-07-15 10:16:32 +08:00
{
if ($reason !== $this->reason) {
2023-08-09 14:43:30 +08:00
throw new \LogicException('Cannot reject a rejected promise');
2023-07-15 10:16:32 +08:00
}
}
2023-08-09 14:43:30 +08:00
public function cancel(): void
2023-07-15 10:16:32 +08:00
{
// pass
}
}