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

90 lines
2.0 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 fulfilled.
*
* Thenning off of this promise will invoke the onFulfilled callback
* immediately and ignore other callbacks.
2023-08-09 14:43:30 +08:00
*
* @final
2023-07-15 10:16:32 +08:00
*/
class FulfilledPromise implements PromiseInterface
{
private $value;
2023-08-09 14:43:30 +08:00
/**
* @param mixed $value
*/
2023-07-15 10:16:32 +08:00
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-08-09 14:43:30 +08:00
): PromiseInterface {
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-08-09 14:43:30 +08:00
$queue->add(static function () use ($p, $value, $onFulfilled): void {
2023-07-15 10:16:32 +08:00
if (Is::pending($p)) {
try {
$p->resolve($onFulfilled($value));
} catch (\Throwable $e) {
$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
{
return $unwrap ? $this->value : null;
}
2023-08-09 14:43:30 +08:00
public function getState(): string
2023-07-15 10:16:32 +08:00
{
return self::FULFILLED;
}
2023-08-09 14:43:30 +08:00
public function resolve($value): void
2023-07-15 10:16:32 +08:00
{
if ($value !== $this->value) {
2023-08-09 14:43:30 +08:00
throw new \LogicException('Cannot resolve a fulfilled 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
{
2023-08-09 14:43:30 +08:00
throw new \LogicException('Cannot reject a fulfilled 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
}
}