Phase 0: Fundament für Inhaus
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 1m14s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 1m12s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 1m7s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 1m19s
CI / PHP 8.3 / mysql:8.0 (pull_request) Successful in 1m32s
CI / PHP 8.4 / mysql:8.0 (pull_request) Successful in 1m22s
CI / PHP 8.4 / mysql:8.4 (pull_request) Successful in 1m32s
CI / PHP 8.3 / mysql:8.4 (pull_request) Successful in 1m35s
CI / Build-Artefakte aktuell (pull_request) Failing after 1m7s

- Laravel 13 mit Filament 5 (Admin), Inertia 3 + Vue 3 + Vuetify 4 (Material 3)
- Anmeldung über Fortify (Login, Passwort vergessen/ändern), keine Selbstregistrierung
- Profil mit Profilbild (WebP in festen Größen), Personenseiten, Header mit Avatar-Menü
- Material-3-Farbschema aus der Primärfarbe, hell/dunkel/System pro Person
- Basis-Branding (Portalname, Logo, Primärfarbe) im Admin unter „Erscheinungsbild“
- Benutzerverwaltung im Admin, Zugang vorläufig über is_admin
- vendor/ (ohne Dev-Pakete) und Frontend-Build mitversioniert, Dev-Pakete in vendor-dev/
- PHPUnit-Tests gegen MySQL/MariaDB, Forgejo-CI-Matrix, Docker-Entwicklungsumgebung
- VERSION, CHANGELOG.md und CONTRIBUTING.md mit Release-Ablauf

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-25 20:35:30 +00:00
parent 7197eaebf2
commit 9c0f8de791
15771 changed files with 1564103 additions and 5 deletions

View file

@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
/**
* Exception thrown when too many errors occur in the some() or any() methods.
*/
class AggregateException extends RejectionException
{
public function __construct(string $msg, array $reasons)
{
parent::__construct(
$reasons,
sprintf('%s; %d rejected promises', $msg, count($reasons))
);
}
}

View file

@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
/**
* Exception that is set as the reason for a promise that has been cancelled.
*/
class CancellationException extends RejectionException
{
}

View file

@ -0,0 +1,195 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
use Generator;
/**
* Creates a promise that is resolved using a generator that yields values or
* promises (somewhat similar to C#'s async keyword).
*
* When called, the Coroutine::of method will start an instance of the generator
* and returns a promise that is fulfilled with its final yielded value.
*
* Control is returned back to the generator when the yielded promise settles.
* This can lead to less verbose code when doing lots of sequential async calls
* with minimal processing in between.
*
* use GuzzleHttp\Promise;
*
* function createPromise($value) {
* return new Promise\FulfilledPromise($value);
* }
*
* $promise = Promise\Coroutine::of(function () {
* $value = (yield createPromise('a'));
* try {
* $value = (yield createPromise($value . 'b'));
* } catch (\Throwable $e) {
* // The promise was rejected.
* }
* yield $value . 'c';
* });
*
* // Outputs "abc"
* $promise->then(function ($v) { echo $v; });
*
* @template TValue = mixed
* @template TReason = mixed
*
* @implements PromiseInterface<TValue, TReason>
*
* @see https://github.com/petkaantonov/bluebird/blob/master/API.md#generators inspiration
*/
final class Coroutine implements PromiseInterface
{
use NonSerializableTrait;
/**
* @var PromiseInterface<mixed, mixed>|null
*/
private ?PromiseInterface $currentPromise = null;
/**
* @var Generator<mixed, mixed, mixed, mixed>
*/
private Generator $generator;
/**
* @var Promise<TValue, TReason>
*/
private PromiseInterface $result;
/**
* @param callable(): Generator<mixed, mixed, mixed, mixed> $generatorFn
*/
public function __construct(callable $generatorFn)
{
$this->generator = $generatorFn();
$this->result = new Promise(function (): void {
while (isset($this->currentPromise)) {
$this->currentPromise->wait();
}
});
try {
$this->nextCoroutine($this->generator->current());
} catch (\Throwable $throwable) {
$this->result->reject($throwable);
}
}
/**
* Create a new coroutine.
*
* @param callable(): Generator<mixed, mixed, mixed, mixed> $generatorFn
*
* @return self<mixed, mixed>
*/
public static function of(callable $generatorFn): self
{
return new self($generatorFn);
}
/**
* @template TFulfilledValue = never
* @template TFulfilledReason = never
* @template TRejectedValue = never
* @template TRejectedReason = never
*
* @param (callable(TValue): (TFulfilledValue|PromiseInterface<TFulfilledValue, TFulfilledReason>))|null $onFulfilled Invoked when the promise fulfills.
* @param (callable(TReason): (TRejectedValue|PromiseInterface<TRejectedValue, TRejectedReason>))|null $onRejected Invoked when the promise is rejected.
*
* @return PromiseInterface<($onFulfilled is null ? TValue : TFulfilledValue)|($onRejected is null ? never : TRejectedValue), ($onFulfilled is null ? never : TFulfilledReason|\Throwable)|($onRejected is null ? TReason : TRejectedReason|\Throwable)>
*/
public function then(
?callable $onFulfilled = null,
?callable $onRejected = null
): PromiseInterface {
return $this->result->then($onFulfilled, $onRejected);
}
/**
* @template TRejectedValue = never
* @template TRejectedReason = never
*
* @param callable(TReason): (TRejectedValue|PromiseInterface<TRejectedValue, TRejectedReason>) $onRejected Invoked when the promise is rejected.
*
* @return PromiseInterface<TValue|TRejectedValue, TRejectedReason|\Throwable>
*/
public function otherwise(callable $onRejected): PromiseInterface
{
return $this->result->otherwise($onRejected);
}
public function wait(bool $unwrap = true)
{
return $this->result->wait($unwrap);
}
public function getState(): string
{
return $this->result->getState();
}
public function resolve($value = null): void
{
$this->result->resolve($value);
}
public function reject($reason): void
{
$this->result->reject($reason);
}
public function cancel(): void
{
if (isset($this->currentPromise)) {
$this->currentPromise->cancel();
}
$this->result->cancel();
}
private function nextCoroutine($yielded): void
{
$this->currentPromise = Create::promiseFor($yielded)
->then([$this, '_handleSuccess'], [$this, '_handleFailure']);
}
/**
* @internal
*/
public function _handleSuccess($value): void
{
$this->currentPromise = null;
try {
$next = $this->generator->send($value);
if ($this->generator->valid()) {
$this->nextCoroutine($next);
} else {
$this->result->resolve($value);
}
} catch (\Throwable $throwable) {
$this->result->reject($throwable);
}
}
/**
* @internal
*/
public function _handleFailure($reason): void
{
$this->currentPromise = null;
try {
$nextYield = $this->generator->throw(Create::exceptionFor($reason));
// The throw was caught, so keep iterating on the coroutine
$this->nextCoroutine($nextYield);
} catch (\Throwable $throwable) {
$this->result->reject($throwable);
}
}
}

View file

@ -0,0 +1,109 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
final class Create
{
private function __construct()
{
}
/**
* Returns `$value` when it is already a Guzzle promise, wraps foreign
* thenables in a Guzzle promise, or returns a fulfilled promise for plain
* values.
*
* @template TValue
* @template TPromise of PromiseInterface<mixed, mixed> = PromiseInterface<mixed, mixed>
*
* @param TValue|TPromise $value Promise or value.
*
* @return ($value is PromiseInterface ? TPromise : FulfilledPromise<TValue, never>)
*/
public static function promiseFor($value): PromiseInterface
{
if ($value instanceof PromiseInterface) {
return $value;
}
// Return a Guzzle promise that shadows the given promise.
if (is_object($value) && method_exists($value, 'then')) {
$wfn = method_exists($value, 'wait') ? [$value, 'wait'] : null;
$cfn = method_exists($value, 'cancel') ? [$value, 'cancel'] : null;
$promise = new Promise($wfn, $cfn);
$value->then([$promise, 'resolve'], [$promise, 'reject']);
return $promise;
}
return new FulfilledPromise($value);
}
/**
* Returns `$reason` when it is already a promise, or returns a rejected
* promise for plain reasons.
*
* @template TReason
* @template TValue = never
* @template TPromise of PromiseInterface<mixed, mixed> = PromiseInterface<mixed, mixed>
*
* @param TReason|TPromise $reason Promise or reason.
*
* @return ($reason is PromiseInterface ? TPromise : RejectedPromise<TValue, TReason>)
*/
public static function rejectionFor($reason): PromiseInterface
{
if ($reason instanceof PromiseInterface) {
return $reason;
}
return new RejectedPromise($reason);
}
/**
* Returns throwable reasons as-is, or wraps non-throwable reasons in
* `RejectionException`.
*
* @template TReason
*
* @param TReason $reason
*/
public static function exceptionFor($reason): \Throwable
{
if ($reason instanceof \Throwable) {
return $reason;
}
return new RejectionException($reason);
}
/**
* Returns an iterator for arrays, iterators, iterator aggregates, and
* traversables.
*
* @template TKey of array-key
* @template TValue
*
* @param iterable<TKey, TValue> $value
*
* @return \Iterator<TKey, TValue>
*/
public static function iterFor(iterable $value): \Iterator
{
if ($value instanceof \Iterator) {
return $value;
}
if (is_array($value)) {
return new \ArrayIterator($value);
}
if ($value instanceof \IteratorAggregate) {
return self::iterFor($value->getIterator());
}
return new \IteratorIterator($value);
}
}

118
vendor/guzzlehttp/promises/src/Each.php vendored Normal file
View file

@ -0,0 +1,118 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
final class Each
{
private function __construct()
{
}
/**
* Given an iterator that yields promises or values, returns a promise that
* is fulfilled with a null value when the iterator has been consumed or
* the aggregate promise has been fulfilled or rejected.
*
* $onFulfilled is a function that accepts the fulfilled value, iterable
* key, and the aggregate promise. The callback can invoke any necessary
* side effects and choose to resolve or reject the aggregate if needed.
*
* $onRejected is a function that accepts the rejection reason, iterable
* key, and the aggregate promise. The callback can invoke any necessary
* side effects and choose to resolve or reject the aggregate if needed.
*
* The config array accepts a concurrency option matching {@see ofLimit}.
* Other config keys are ignored by this wrapper.
*
* @template TKey of array-key
* @template TValue
* @template TReason
*
* @param iterable<TKey, TValue|PromiseInterface<TValue, TReason>> $iterable Iterator or array to iterate over.
* @param (callable(TValue, TKey, PromiseInterface<mixed, mixed>): mixed)|null $onFulfilled
* @param (callable(TReason, TKey, PromiseInterface<mixed, mixed>): mixed)|null $onRejected
* @param array{concurrency?: int|(callable(int): int)} $config Configuration options.
*
* @return PromiseInterface<mixed, mixed>
*/
public static function of(
iterable $iterable,
?callable $onFulfilled = null,
?callable $onRejected = null,
array $config = []
): PromiseInterface {
$eachConfig = [];
if (null !== $onFulfilled) {
$eachConfig['fulfilled'] = $onFulfilled;
}
if (null !== $onRejected) {
$eachConfig['rejected'] = $onRejected;
}
if (isset($config['concurrency'])) {
$eachConfig['concurrency'] = $config['concurrency'];
}
return (new EachPromise($iterable, $eachConfig))->promise();
}
/**
* Like of, but only allows a certain number of outstanding promises at any
* given time.
*
* $concurrency may be an integer or a function that accepts the number of
* pending promises and returns a numeric concurrency limit value to allow
* for a dynamic concurrency size.
*
* @template TKey of array-key
* @template TValue
* @template TReason
*
* @param iterable<TKey, TValue|PromiseInterface<TValue, TReason>> $iterable
* @param int|(callable(int): int) $concurrency
* @param (callable(TValue, TKey, PromiseInterface<mixed, mixed>): mixed)|null $onFulfilled
* @param (callable(TReason, TKey, PromiseInterface<mixed, mixed>): mixed)|null $onRejected
*
* @return PromiseInterface<mixed, mixed>
*/
public static function ofLimit(
iterable $iterable,
$concurrency,
?callable $onFulfilled = null,
?callable $onRejected = null
): PromiseInterface {
return self::of($iterable, $onFulfilled, $onRejected, ['concurrency' => $concurrency]);
}
/**
* Like ofLimit, but rejects the aggregate promise on the first rejection.
*
* @template TKey of array-key
* @template TValue
* @template TReason
*
* @param iterable<TKey, TValue|PromiseInterface<TValue, TReason>> $iterable
* @param int|(callable(int): int) $concurrency
* @param (callable(TValue, TKey, PromiseInterface<mixed, mixed>): mixed)|null $onFulfilled
*
* @return PromiseInterface<mixed, mixed>
*/
public static function ofLimitAll(
iterable $iterable,
$concurrency,
?callable $onFulfilled = null
): PromiseInterface {
return self::ofLimit(
$iterable,
$concurrency,
$onFulfilled,
function ($reason, $idx, PromiseInterface $aggregate): void {
$aggregate->reject($reason);
}
);
}
}

View file

@ -0,0 +1,295 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
/**
* Represents a promise that iterates over many promises and invokes
* side-effect functions in the process.
*
* @template TKey of array-key
* @template TValue
* @template TReason
*
* @implements PromisorInterface<mixed, mixed>
*
* @final
*/
class EachPromise implements PromisorInterface
{
use NonSerializableTrait;
/** @var array<int, PromiseInterface<mixed, mixed>>|null */
private ?array $pending = [];
private int $nextPendingIndex = 0;
/** @var \Iterator<TKey, TValue|PromiseInterface<TValue, TReason>>|null */
private ?\Iterator $iterable;
/** @var (callable(int): int)|int|null */
private $concurrency;
/** @var (callable(TValue, TKey, PromiseInterface<mixed, mixed>): mixed)|null */
private $onFulfilled;
/** @var (callable(TReason, TKey, PromiseInterface<mixed, mixed>): mixed)|null */
private $onRejected;
/** @var Promise<mixed, mixed>|null */
private ?Promise $aggregate = null;
private ?bool $mutex = null;
private bool $stepWhileLocked = false;
/**
* Configuration hash can include the following key value pairs:
*
* - fulfilled: (callable) Invoked when a promise fulfills. The function
* is invoked with three arguments: the fulfillment value, the index
* position from the iterable list of the promise, and the aggregate
* promise that manages all of the promises. The aggregate promise may
* be resolved from within the callback to short-circuit the promise.
* - rejected: (callable) Invoked when a promise is rejected. The
* function is invoked with three arguments: the rejection reason, the
* index position from the iterable list of the promise, and the
* aggregate promise that manages all of the promises. The aggregate
* promise may be resolved from within the callback to short-circuit
* the promise.
* - concurrency: (integer) Pass this configuration option to limit the
* allowed number of outstanding concurrently executing promises,
* creating a capped pool of promises. There is no limit by default.
*
* @param iterable<TKey, TValue|PromiseInterface<TValue, TReason>> $iterable Promises or values to iterate.
* @param array{
* fulfilled?: callable(TValue, TKey, PromiseInterface<mixed, mixed>): mixed,
* rejected?: callable(TReason, TKey, PromiseInterface<mixed, mixed>): mixed,
* concurrency?: int|(callable(int): int)
* } $config Configuration options
*/
public function __construct(iterable $iterable, array $config = [])
{
$this->iterable = Create::iterFor($iterable);
if (isset($config['concurrency'])) {
$this->concurrency = $config['concurrency'];
}
if (isset($config['fulfilled'])) {
$this->onFulfilled = $config['fulfilled'];
}
if (isset($config['rejected'])) {
$this->onRejected = $config['rejected'];
}
}
/**
* @return PromiseInterface<mixed, mixed>
*/
public function promise(): PromiseInterface
{
if ($this->aggregate) {
return $this->aggregate;
}
try {
$this->createPromise();
$this->iterable->rewind();
$this->refillPending();
if (!$this->pending) {
Utils::queue()->add(function (): void {
if (!$this->aggregate || Is::settled($this->aggregate)) {
return;
}
try {
$this->checkIfFinished();
} catch (\Throwable $e) {
$this->aggregate->reject($e);
}
});
}
} catch (\Throwable $e) {
$this->aggregate->reject($e);
}
return $this->aggregate;
}
private function createPromise(): void
{
$this->mutex = false;
$this->aggregate = new Promise(function (): void {
while (true) {
if ($this->checkIfFinished()) {
return;
}
reset($this->pending);
// Consume a potentially fluctuating list of promises while
// ensuring that indexes are maintained (precluding array_shift).
while ($promise = current($this->pending)) {
next($this->pending);
$promise->wait();
if (Is::settled($this->aggregate)) {
return;
}
}
// Refill and re-sweep; give up only when nothing remains.
$this->refillPending();
if (Is::settled($this->aggregate) || !$this->pending) {
return;
}
}
});
// Clear the references when the promise is resolved.
$clearFn = function (): void {
$this->iterable = $this->concurrency = $this->pending = null;
$this->onFulfilled = $this->onRejected = null;
$this->nextPendingIndex = 0;
};
$this->aggregate->then($clearFn, $clearFn);
}
private function refillPending(): void
{
if (!$this->concurrency) {
// Add all pending promises.
while ($this->addPending() && $this->advanceIterator()) {
}
return;
}
// Add only up to N pending promises.
$concurrency = is_callable($this->concurrency)
? ($this->concurrency)(count($this->pending))
: $this->concurrency;
// The callable can settle the aggregate; admit nothing more.
if (Is::settled($this->aggregate)) {
return;
}
$concurrency = max($concurrency - count($this->pending), 0);
// Concurrency may be set to 0 to disallow new promises.
if (!$concurrency) {
return;
}
// Add the first pending promise.
$this->addPending();
// Note this is special handling for concurrency=1 so that we do
// not advance the iterator after adding the first promise. This
// helps work around issues with generators that might not have the
// next value to yield until promise callbacks are called.
while (--$concurrency
&& $this->advanceIterator()
&& $this->addPending()) {
}
}
private function addPending(): bool
{
if (!$this->iterable || !$this->iterable->valid()) {
return false;
}
$promise = Create::promiseFor($this->iterable->current());
$key = $this->iterable->key();
// Iterable keys may not be unique, so we use a counter to
// guarantee uniqueness
$idx = $this->nextPendingIndex++;
$this->pending[$idx] = $promise->then(
function ($value) use ($idx, $key): void {
if ($this->onFulfilled) {
($this->onFulfilled)(
$value,
$key,
$this->aggregate
);
}
$this->step($idx);
},
function ($reason) use ($idx, $key): void {
if ($this->onRejected) {
($this->onRejected)(
$reason,
$key,
$this->aggregate
);
}
$this->step($idx);
}
);
return true;
}
private function advanceIterator(): bool
{
// Place a lock on the iterator so that we ensure to not recurse,
// preventing fatal generator errors.
if ($this->mutex) {
$this->stepWhileLocked = true;
return false;
}
$this->mutex = true;
try {
$this->iterable->next();
$this->mutex = false;
} catch (\Throwable $e) {
$this->aggregate->reject($e);
$this->mutex = false;
return false;
}
// Run the completion check that locked steps skipped.
if ($this->stepWhileLocked) {
$this->stepWhileLocked = false;
if (!Is::settled($this->aggregate)) {
$this->checkIfFinished();
}
}
return true;
}
private function step(int $idx): void
{
// If the promise was already resolved, then ignore this step.
if (Is::settled($this->aggregate)) {
return;
}
unset($this->pending[$idx]);
// Only refill pending promises if we are not locked, preventing the
// EachPromise to recursively invoke the provided iterator, which
// cause a fatal error: "Cannot resume an already running generator"
if ($this->advanceIterator() && !$this->checkIfFinished()) {
// Add more pending promises if possible.
$this->refillPending();
}
}
/** @phpstan-impure */
private function checkIfFinished(): bool
{
if (!$this->pending && !$this->iterable->valid()) {
// Resolve the promise if there's nothing left to do.
$this->aggregate->resolve(null);
return true;
}
return false;
}
}

View file

@ -0,0 +1,111 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
/**
* A promise that has been fulfilled.
*
* Thenning off of this promise will invoke the onFulfilled callback
* immediately and ignore other callbacks.
*
* @template TValue = mixed
* @template TReason = never
*
* @implements PromiseInterface<TValue, TReason>
*
* @final
*/
class FulfilledPromise implements PromiseInterface
{
/** @var TValue */
private $value;
/**
* @param TValue $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;
}
/**
* @template TFulfilledValue = never
* @template TFulfilledReason = never
* @template TRejectedValue = never
* @template TRejectedReason = never
*
* @param (callable(TValue): (TFulfilledValue|PromiseInterface<TFulfilledValue, TFulfilledReason>))|null $onFulfilled Invoked when the promise fulfills.
* @param (callable(TReason): (TRejectedValue|PromiseInterface<TRejectedValue, TRejectedReason>))|null $onRejected Invoked when the promise is rejected.
*
* @return ($onFulfilled is null ? self<TValue, TReason> : PromiseInterface<TFulfilledValue, TFulfilledReason|\Throwable>)
*/
public function then(
?callable $onFulfilled = null,
?callable $onRejected = null
): PromiseInterface {
// Return itself if there is no onFulfilled function.
if (!$onFulfilled) {
return $this;
}
$queue = Utils::queue();
$p = new Promise([$queue, 'run']);
$value = $this->value;
$queue->add(static function () use ($p, $value, $onFulfilled): void {
if (Is::pending($p)) {
try {
$p->resolve($onFulfilled($value));
} catch (\Throwable $e) {
$p->reject($e);
}
}
});
return $p;
}
/**
* @param callable(TReason): mixed $onRejected Invoked when the promise is rejected.
*
* @return self<TValue, TReason>
*/
public function otherwise(callable $onRejected): PromiseInterface
{
return $this->then(null, $onRejected);
}
public function wait(bool $unwrap = true)
{
return $unwrap ? $this->value : null;
}
public function getState(): string
{
return self::FULFILLED;
}
public function resolve($value = null): void
{
if ($value !== $this->value) {
throw new \LogicException('Cannot resolve a fulfilled promise');
}
}
public function reject($reason): void
{
throw new \LogicException('Cannot reject a fulfilled promise');
}
public function cancel(): void
{
// pass
}
}

44
vendor/guzzlehttp/promises/src/Is.php vendored Normal file
View file

@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
final class Is
{
private function __construct()
{
}
/**
* Returns true if a promise is pending.
*/
public static function pending(PromiseInterface $promise): bool
{
return $promise->getState() === PromiseInterface::PENDING;
}
/**
* Returns true if a promise is fulfilled or rejected.
*/
public static function settled(PromiseInterface $promise): bool
{
return $promise->getState() !== PromiseInterface::PENDING;
}
/**
* Returns true if a promise is fulfilled.
*/
public static function fulfilled(PromiseInterface $promise): bool
{
return $promise->getState() === PromiseInterface::FULFILLED;
}
/**
* Returns true if a promise is rejected.
*/
public static function rejected(PromiseInterface $promise): bool
{
return $promise->getState() === PromiseInterface::REJECTED;
}
}

View file

@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
/**
* @internal
*/
trait NonSerializableTrait
{
public function __serialize(): array
{
throw new \LogicException(static::class.' should never be serialized');
}
public function __unserialize(array $data): void
{
throw new \LogicException(static::class.' should never be unserialized');
}
}

View file

@ -0,0 +1,323 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
/**
* Promises/A+ implementation that avoids recursion when possible.
*
* @template TValue = mixed
* @template TReason = mixed
*
* @implements PromiseInterface<TValue, TReason>
*
* @see https://promisesaplus.com/
*
* @final
*/
class Promise implements PromiseInterface
{
use NonSerializableTrait;
/** @var self::PENDING|self::FULFILLED|self::REJECTED */
private string $state = self::PENDING;
/** @var TValue|TReason|PromiseInterface<TValue, TReason>|null */
private $result;
/** @var (callable(): void)|null */
private $cancelFn;
/** @var (callable(bool): void)|null */
private $waitFn;
/** @var list<Promise<mixed, mixed>>|null */
private ?array $waitList = null;
/** @var list<array{0: PromiseInterface<mixed, mixed>, 1: callable|null, 2: callable|null}>|null */
private ?array $handlers = [];
/**
* @param (callable(bool): void)|null $waitFn Fn that when invoked resolves the promise.
* @param (callable(): void)|null $cancelFn Fn that when invoked cancels the promise.
*/
public function __construct(
?callable $waitFn = null,
?callable $cancelFn = null
) {
$this->waitFn = $waitFn;
$this->cancelFn = $cancelFn;
}
/**
* @template TFulfilledValue = never
* @template TFulfilledReason = never
* @template TRejectedValue = never
* @template TRejectedReason = never
*
* @param (callable(TValue): (TFulfilledValue|PromiseInterface<TFulfilledValue, TFulfilledReason>))|null $onFulfilled Invoked when the promise fulfills.
* @param (callable(TReason): (TRejectedValue|PromiseInterface<TRejectedValue, TRejectedReason>))|null $onRejected Invoked when the promise is rejected.
*
* @return PromiseInterface<($onFulfilled is null ? TValue : TFulfilledValue)|($onRejected is null ? never : TRejectedValue), ($onFulfilled is null ? never : TFulfilledReason|\Throwable)|($onRejected is null ? TReason : TRejectedReason|\Throwable)>
*/
public function then(
?callable $onFulfilled = null,
?callable $onRejected = null
): PromiseInterface {
if ($this->state === self::PENDING) {
$p = new Promise(null, [$this, 'cancel']);
$this->handlers[] = [$p, $onFulfilled, $onRejected];
$p->waitList = $this->waitList;
$p->waitList[] = $this;
return $p;
}
// Return a fulfilled promise and immediately invoke any callbacks.
if ($this->state === self::FULFILLED) {
$promise = Create::promiseFor($this->result);
return $promise->then($onFulfilled, $onRejected);
}
// It's either cancelled or rejected, so return a rejected promise
// and immediately invoke any callbacks.
$rejection = Create::rejectionFor($this->result);
/** @var PromiseInterface<($onFulfilled is null ? TValue : TFulfilledValue)|($onRejected is null ? never : TRejectedValue), ($onFulfilled is null ? never : TFulfilledReason|\Throwable)|($onRejected is null ? TReason : TRejectedReason|\Throwable)> $promise */
$promise = $onRejected ? $rejection->then(null, $onRejected) : $rejection;
return $promise;
}
/**
* @template TRejectedValue = never
* @template TRejectedReason = never
*
* @param callable(TReason): (TRejectedValue|PromiseInterface<TRejectedValue, TRejectedReason>) $onRejected Invoked when the promise is rejected.
*
* @return PromiseInterface<TValue|TRejectedValue, TRejectedReason|\Throwable>
*/
public function otherwise(callable $onRejected): PromiseInterface
{
return $this->then(null, $onRejected);
}
public function wait(bool $unwrap = true)
{
$this->waitIfPending();
if ($this->result instanceof PromiseInterface) {
return $this->result->wait($unwrap);
}
if ($unwrap) {
if ($this->state === self::FULFILLED) {
return $this->result;
}
// It's rejected so "unwrap" and throw an exception.
throw Create::exceptionFor($this->result);
}
return null;
}
public function getState(): string
{
return $this->state;
}
public function cancel(): void
{
if ($this->state !== self::PENDING) {
return;
}
$this->waitFn = $this->waitList = null;
if ($this->cancelFn) {
$fn = $this->cancelFn;
$this->cancelFn = null;
try {
$fn();
} catch (\Throwable $e) {
$this->reject($e);
}
}
// Reject the promise only if it wasn't rejected in a then callback.
/** @psalm-suppress RedundantCondition */
if ($this->state === self::PENDING) {
$this->reject(new CancellationException('Promise has been cancelled'));
}
}
public function resolve($value = null): void
{
$this->settle(self::FULFILLED, $value);
}
public function reject($reason): void
{
$this->settle(self::REJECTED, $reason);
}
private function settle(string $state, $value): void
{
if ($this->state !== self::PENDING) {
// Ignore calls with the same resolution.
if ($state === $this->state && $value === $this->result) {
return;
}
throw $this->state === $state
? new \LogicException("The promise is already {$state}.")
: new \LogicException("Cannot change a {$this->state} promise to {$state}");
}
if ($value === $this) {
throw new \LogicException('Cannot fulfill or reject a promise with itself');
}
// Clear out the state of the promise but stash the handlers.
$this->state = $state;
$this->result = $value;
$handlers = $this->handlers;
$this->handlers = null;
$this->waitList = $this->waitFn = null;
$this->cancelFn = null;
if (!$handlers) {
return;
}
// If the value was not a settled promise or a thenable, then resolve
// it in the task queue using the correct ID.
if (!is_object($value) || !method_exists($value, 'then')) {
$id = $state === self::FULFILLED ? 1 : 2;
// It's a success, so resolve the handlers in the queue.
Utils::queue()->add(static function () use ($id, $value, $handlers): void {
foreach ($handlers as $handler) {
self::callHandler($id, $value, $handler);
}
});
} elseif ($value instanceof Promise && Is::pending($value)) {
// We can just merge our handlers onto the next promise.
$value->handlers = array_merge($value->handlers, $handlers);
} else {
// Resolve the handlers when the forwarded promise is resolved.
$value->then(
static function ($value) use ($handlers): void {
foreach ($handlers as $handler) {
self::callHandler(1, $value, $handler);
}
},
static function ($reason) use ($handlers): void {
foreach ($handlers as $handler) {
self::callHandler(2, $reason, $handler);
}
}
);
}
}
/**
* Call a stack of handlers using a specific callback index and value.
*
* @param int $index 1 (resolve) or 2 (reject).
* @param mixed $value Value to pass to the callback.
* @param array $handler Array of handler data (promise and callbacks).
*/
private static function callHandler(int $index, $value, array $handler): void
{
/** @var PromiseInterface<mixed, mixed> $promise */
$promise = $handler[0];
// The promise may have been cancelled or resolved before placing
// this thunk in the queue.
if (Is::settled($promise)) {
return;
}
try {
if (isset($handler[$index])) {
/*
* If $f throws an exception, then $handler will be in the exception
* stack trace. Since $handler contains a reference to the callable
* itself we get a circular reference. We clear the $handler
* here to avoid that memory leak.
*/
$f = $handler[$index];
unset($handler);
$promise->resolve($f($value));
} elseif ($index === 1) {
// Forward resolution values as-is.
$promise->resolve($value);
} else {
// Forward rejections down the chain.
$promise->reject($value);
}
} catch (\Throwable $reason) {
$promise->reject($reason);
}
}
private function waitIfPending(): void
{
if ($this->state !== self::PENDING) {
return;
} elseif ($this->waitFn) {
$this->invokeWaitFn();
} elseif ($this->waitList) {
$this->invokeWaitList();
} else {
// If there's no wait function, then reject the promise.
$this->reject('Cannot wait on a promise that has '
.'no internal wait function. You must provide a wait '
.'function when constructing the promise to be able to '
.'wait on a promise.');
}
Utils::queue()->run();
/** @psalm-suppress RedundantCondition */
if ($this->state === self::PENDING) {
$this->reject('Invoking the wait callback did not resolve the promise');
}
}
private function invokeWaitFn(): void
{
try {
$wfn = $this->waitFn;
$this->waitFn = null;
$wfn(true);
} catch (\Throwable $reason) {
if ($this->state === self::PENDING) {
// The promise has not been resolved yet, so reject the promise
// with the exception.
$this->reject($reason);
} else {
// The promise was already resolved, so there's a problem in
// the application.
throw $reason;
}
}
}
private function invokeWaitList(): void
{
$waitList = $this->waitList;
$this->waitList = null;
foreach ($waitList as $result) {
do {
$result->waitIfPending();
$result = $result->result;
} while ($result instanceof Promise);
if ($result instanceof PromiseInterface) {
$result->wait(false);
}
}
}
}

View file

@ -0,0 +1,119 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
/**
* A promise represents the eventual result of an asynchronous operation.
*
* The primary way of interacting with a promise is through its then method,
* which registers callbacks to receive either a promise’s eventual value or
* the reason why the promise cannot be fulfilled.
*
* @template TValue = mixed
* @template TReason = mixed
*
* @see https://promisesaplus.com/
*/
interface PromiseInterface
{
public const PENDING = 'pending';
public const FULFILLED = 'fulfilled';
public const REJECTED = 'rejected';
/**
* Appends fulfillment and rejection handlers to the promise, and returns
* a new promise resolving to the return value of the called handler.
*
* @template TFulfilledValue = never
* @template TFulfilledReason = never
* @template TRejectedValue = never
* @template TRejectedReason = never
*
* @param (callable(TValue): (TFulfilledValue|PromiseInterface<TFulfilledValue, TFulfilledReason>))|null $onFulfilled Invoked when the promise fulfills.
* @param (callable(TReason): (TRejectedValue|PromiseInterface<TRejectedValue, TRejectedReason>))|null $onRejected Invoked when the promise is rejected.
*
* @return PromiseInterface<($onFulfilled is null ? TValue : TFulfilledValue)|($onRejected is null ? never : TRejectedValue), ($onFulfilled is null ? never : TFulfilledReason|\Throwable)|($onRejected is null ? TReason : TRejectedReason|\Throwable)>
*/
public function then(
?callable $onFulfilled = null,
?callable $onRejected = null
): PromiseInterface;
/**
* Appends a rejection handler callback to the promise, and returns a new
* promise resolving to the return value of the callback if it is called,
* or to its original fulfillment value if the promise is instead
* fulfilled.
*
* @template TRejectedValue = never
* @template TRejectedReason = never
*
* @param callable(TReason): (TRejectedValue|PromiseInterface<TRejectedValue, TRejectedReason>) $onRejected Invoked when the promise is rejected.
*
* @return PromiseInterface<TValue|TRejectedValue, TRejectedReason|\Throwable>
*/
public function otherwise(callable $onRejected): PromiseInterface;
/**
* Get the state of the promise ("pending", "rejected", or "fulfilled").
*
* The three states can be checked against the constants defined on
* PromiseInterface: PENDING, FULFILLED, and REJECTED.
*
* The state describes how this promise was settled, not the eventual
* outcome: a promise that was resolved with another promise, directly or
* by returning one from a then() handler, reports FULFILLED while the
* inner promise may still be pending, and wait() can still throw if the
* inner promise rejects. Poll the state only on promises settled with
* plain values, or call wait() first.
*
* @return self::PENDING|self::FULFILLED|self::REJECTED
*
* @see https://github.com/guzzle/promises/issues/101
*/
public function getState(): string;
/**
* Resolve the promise with the given value, or with null if no value is given.
*
* @param TValue|PromiseInterface<TValue, TReason>|null $value
*
* @throws \LogicException if the promise is already settled with a
* conflicting resolution.
*/
public function resolve($value = null): void;
/**
* Reject the promise with the given reason.
*
* @param TReason $reason
*
* @throws \LogicException if the promise is already settled with a
* conflicting resolution.
*/
public function reject($reason): void;
/**
* Cancels the promise if possible.
*
* @see https://github.com/promises-aplus/cancellation-spec/issues/7
*/
public function cancel(): void;
/**
* Waits until the promise completes if possible.
*
* Pass $unwrap as true to unwrap the result of the promise, either
* returning the resolved value or throwing the rejected exception.
*
* If the promise cannot be waited on, then the promise will be rejected.
*
* @return ($unwrap is true ? TValue : null)
*
* @throws \LogicException if the promise has no wait function or if the
* promise does not settle after waiting.
*/
public function wait(bool $unwrap = true);
}

View file

@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
/**
* Interface used with classes that return a promise.
*
* @template TValue = mixed
* @template TReason = mixed
*/
interface PromisorInterface
{
/**
* Returns a promise.
*
* @return PromiseInterface<TValue, TReason>
*/
public function promise(): PromiseInterface;
}

View file

@ -0,0 +1,120 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
/**
* A promise that has been rejected.
*
* Thenning off of this promise will invoke the onRejected callback
* immediately and ignore other callbacks.
*
* @template TValue = never
* @template TReason = mixed
*
* @implements PromiseInterface<TValue, TReason>
*
* @final
*/
class RejectedPromise implements PromiseInterface
{
/** @var TReason */
private $reason;
/**
* @param TReason $reason
*/
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;
}
/**
* @template TFulfilledValue = never
* @template TFulfilledReason = never
* @template TRejectedValue = never
* @template TRejectedReason = never
*
* @param (callable(TValue): (TFulfilledValue|PromiseInterface<TFulfilledValue, TFulfilledReason>))|null $onFulfilled Invoked when the promise fulfills.
* @param (callable(TReason): (TRejectedValue|PromiseInterface<TRejectedValue, TRejectedReason>))|null $onRejected Invoked when the promise is rejected.
*
* @return ($onRejected is null ? self<TValue, TReason> : PromiseInterface<TRejectedValue, TRejectedReason|\Throwable>)
*/
public function then(
?callable $onFulfilled = null,
?callable $onRejected = null
): PromiseInterface {
// 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']);
$queue->add(static function () use ($p, $reason, $onRejected): void {
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;
}
/**
* @template TRejectedValue = never
* @template TRejectedReason = never
*
* @param callable(TReason): (TRejectedValue|PromiseInterface<TRejectedValue, TRejectedReason>) $onRejected Invoked when the promise is rejected.
*
* @return PromiseInterface<TRejectedValue, TRejectedReason|\Throwable>
*/
public function otherwise(callable $onRejected): PromiseInterface
{
return $this->then(null, $onRejected);
}
public function wait(bool $unwrap = true)
{
if ($unwrap) {
throw Create::exceptionFor($this->reason);
}
return null;
}
public function getState(): string
{
return self::REJECTED;
}
public function resolve($value = null): void
{
throw new \LogicException('Cannot resolve a rejected promise');
}
public function reject($reason): void
{
if ($reason !== $this->reason) {
throw new \LogicException('Cannot reject a rejected promise');
}
}
public function cancel(): void
{
// pass
}
}

View file

@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
/**
* A special exception that is thrown when waiting on a rejected promise.
*
* The reason value is available via the getReason() method.
*/
class RejectionException extends \RuntimeException
{
/** @var mixed Rejection reason. */
private $reason;
/**
* @param mixed $reason Rejection reason.
* @param string|null $description Optional description.
*/
public function __construct($reason, ?string $description = null)
{
$this->reason = $reason;
$message = 'The promise was rejected';
if ($description) {
$message .= ' with reason: '.$description;
} elseif (is_string($reason)
|| (is_object($reason) && method_exists($reason, '__toString'))
) {
$message .= ' with reason: '.$this->reason;
} elseif ($reason instanceof \JsonSerializable) {
$message .= ' with reason: '.json_encode($this->reason, JSON_PRETTY_PRINT);
}
parent::__construct($message);
}
/**
* Returns the rejection reason.
*
* @return mixed
*/
public function getReason()
{
return $this->reason;
}
}

View file

@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
/**
* A task queue that executes tasks in a FIFO order.
*
* This task queue class is used to settle promises asynchronously and
* maintains a constant stack size. You can use the task queue asynchronously
* by calling the `run()` function of the global task queue in an event loop.
*
* GuzzleHttp\Promise\Utils::queue()->run();
*
* @final
*/
class TaskQueue implements TaskQueueInterface
{
use NonSerializableTrait;
private bool $enableShutdown = true;
/** @var list<callable(): void> */
private array $queue = [];
public function __construct(bool $withShutdown = true)
{
if ($withShutdown) {
register_shutdown_function(function (): void {
if ($this->enableShutdown) {
// Only run the tasks if an E_ERROR didn't occur.
$err = error_get_last();
if (!$err || ($err['type'] ^ E_ERROR)) {
$this->run();
}
}
});
}
}
public function isEmpty(): bool
{
return !$this->queue;
}
/**
* @param callable(): void $task
*/
public function add(callable $task): void
{
$this->queue[] = $task;
}
public function run(): void
{
while ($task = array_shift($this->queue)) {
/** @var callable(): void $task */
$task();
}
}
/**
* The task queue will be run and exhausted by default when the process
* exits IFF the exit is not the result of a PHP E_ERROR error.
*
* You can disable running the automatic shutdown of the queue by calling
* this function. If you disable the task queue shutdown process, then you
* MUST either run the task queue (as a result of running your event loop
* or manually using the run() method) or wait on each outstanding promise.
*
* Note: This shutdown will occur before any destructors are triggered.
*/
public function disableShutdown(): void
{
$this->enableShutdown = false;
}
}

View file

@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
interface TaskQueueInterface
{
/**
* Returns true if the queue is empty.
*/
public function isEmpty(): bool;
/**
* Adds a task to the queue that will be executed the next time run is
* called.
*
* @param callable(): void $task
*/
public function add(callable $task): void;
/**
* Execute all of the pending task in the queue.
*/
public function run(): void;
}

390
vendor/guzzlehttp/promises/src/Utils.php vendored Normal file
View file

@ -0,0 +1,390 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Promise;
final class Utils
{
private function __construct()
{
}
/**
* Get the global task queue used for promise resolution.
*
* This task queue MUST be run in an event loop in order for promises to be
* settled asynchronously. It will be automatically run when synchronously
* waiting on a promise.
*
* <code>
* while ($eventLoop->isRunning()) {
* GuzzleHttp\Promise\Utils::queue()->run();
* }
* </code>
*
* @param TaskQueueInterface|null $assign Optionally specify a new queue instance.
*/
public static function queue(?TaskQueueInterface $assign = null): TaskQueueInterface
{
static $queue;
if ($assign) {
$queue = $assign;
} elseif (!$queue) {
$queue = new TaskQueue();
}
return $queue;
}
/**
* Adds a task to the global queue and returns a promise that is fulfilled
* or rejected with the task result.
*
* @template TValue
*
* @param callable(): TValue $task Task function to run.
*
* @return PromiseInterface<TValue, \Throwable>
*/
public static function task(callable $task): PromiseInterface
{
$queue = self::queue();
$promise = new Promise([$queue, 'run']);
$queue->add(function () use ($task, $promise): void {
try {
if (Is::pending($promise)) {
$promise->resolve($task());
}
} catch (\Throwable $e) {
$promise->reject($e);
}
});
return $promise;
}
/**
* Synchronously waits on a promise to settle and returns an inspection
* state array.
*
* Returns a state associative array containing a "state" key mapping to a
* valid promise state. If the state of the promise is "fulfilled", the
* array will contain a "value" key mapping to the fulfilled value of the
* promise. If the promise is rejected, the array will contain a "reason"
* key mapping to the rejection reason of the promise.
*
* @template TValue
* @template TReason
*
* @param PromiseInterface<TValue, TReason> $promise Promise to inspect.
*
* @return array{state: PromiseInterface::FULFILLED, value: TValue}|array{state: PromiseInterface::REJECTED, reason: TReason|\Throwable}|array{state: PromiseInterface::PENDING}
*/
public static function inspect(PromiseInterface $promise): array
{
$result = null;
$getResult = static function () use (&$result): ?array {
return $result;
};
$inspection = $promise->then(
static function ($value) use (&$result): void {
$result = ['state' => PromiseInterface::FULFILLED, 'value' => $value];
},
static function ($reason) use (&$result): void {
$result = ['state' => PromiseInterface::REJECTED, 'reason' => $reason];
}
);
try {
$inspection->wait(false);
} catch (\Throwable $e) {
$settled = $getResult();
if (null !== $settled) {
return $settled;
}
if (Is::settled($promise)) {
try {
self::queue()->run();
} catch (\Throwable $queueError) {
return ['state' => PromiseInterface::REJECTED, 'reason' => $queueError];
}
$settled = $getResult();
if (null !== $settled) {
return $settled;
}
}
return ['state' => PromiseInterface::REJECTED, 'reason' => $e];
}
return $getResult() ?? ['state' => $promise->getState()];
}
/**
* Waits on all of the provided promises, but does not unwrap rejected
* promises as a thrown exception.
*
* Returns an array of inspection state arrays keyed like the input
* iterable.
*
* @see inspect for the inspection state array format.
*
* @template TKey of array-key
* @template TValue
* @template TReason
*
* @param iterable<TKey, PromiseInterface<TValue, TReason>> $promises Traversable of promises to wait upon.
*
* @return array<TKey, array{state: PromiseInterface::FULFILLED, value: TValue}|array{state: PromiseInterface::REJECTED, reason: TReason|\Throwable}|array{state: PromiseInterface::PENDING}>
*/
public static function inspectAll(iterable $promises): array
{
$results = [];
foreach ($promises as $key => $promise) {
$results[$key] = self::inspect($promise);
}
return $results;
}
/**
* Waits on all of the provided promises and returns the fulfilled values.
*
* Returns an array that contains the value of each promise (in the same
* order the promises were provided). An exception is thrown if any of the
* promises are rejected.
*
* @template TKey of array-key
* @template TValue
* @template TReason
*
* @param iterable<TKey, PromiseInterface<TValue, TReason>> $promises Iterable of PromiseInterface objects to wait on.
*
* @return array<TKey, TValue>
*
* @throws \Throwable on error
*/
public static function unwrap(iterable $promises): array
{
$results = [];
foreach ($promises as $key => $promise) {
$results[$key] = $promise->wait();
}
return $results;
}
/**
* Given an array of promises, return a promise that is fulfilled when all
* the items in the array are fulfilled.
*
* The promise's fulfillment value is an array with fulfillment values at
* respective positions to the original array. If any promise in the array
* rejects, the returned promise is rejected with the rejection reason.
*
* The config array accepts a concurrency option for lazy iterables. Other
* config keys are ignored by this wrapper.
*
* @template TKey of array-key
* @template TValue
* @template TReason
*
* @param iterable<TKey, TValue|PromiseInterface<TValue, TReason>> $promises Promises or values.
* @param bool $recursive If true, resolves newly-added entries until no unprocessed entries or pending promises remain.
* @param array{concurrency?: int|(callable(int): int)} $config Configuration options.
*
* @return PromiseInterface<array<TKey, TValue>, TReason|\Throwable>
*/
public static function all(iterable $promises, bool $recursive = false, array $config = []): PromiseInterface
{
$results = [];
$promise = Each::of(
$promises,
function ($value, $idx) use (&$results): void {
$results[$idx] = $value;
},
function ($reason, $idx, PromiseInterface $aggregate): void {
if (Is::pending($aggregate)) {
$aggregate->reject($reason);
}
},
$config
)->then(function () use (&$results) {
ksort($results);
return $results;
});
if (true === $recursive) {
$promise = $promise->then(function ($results) use (&$promises, $config) {
if (self::shouldRecurse($promises, $results)) {
return self::all($promises, true, $config);
}
return $results;
});
}
return $promise;
}
/**
* Initiate a competitive race between multiple promises or values (values
* will become immediately fulfilled promises).
*
* When count amount of promises have been fulfilled, the returned promise
* is fulfilled with an array that contains the fulfillment values of the
* winners, in the order they appear in the input.
*
* This promise is rejected with a {@see AggregateException} if the number
* of fulfilled promises is less than the desired $count.
*
* @template TValue
* @template TReason
*
* @param int $count Total number of promises.
* @param iterable<TValue|PromiseInterface<TValue, TReason>> $promises Promises or values.
*
* @return PromiseInterface<list<TValue>, \Throwable>
*/
public static function some(int $count, iterable $promises): PromiseInterface
{
$results = [];
$rejections = [];
$promise = Each::of(
$promises,
function ($value, $idx, PromiseInterface $p) use (&$results, $count): void {
if (Is::settled($p)) {
return;
}
$results[$idx] = $value;
if (count($results) >= $count) {
$p->resolve(null);
}
},
function ($reason) use (&$rejections): void {
$rejections[] = $reason;
}
)->then(
function () use (&$results, &$rejections, $count) {
if (count($results) !== $count) {
throw new AggregateException(
'Not enough promises to fulfill count',
$rejections
);
}
ksort($results);
return array_values($results);
}
);
/** @var PromiseInterface<list<TValue>, \Throwable> $promise */
return $promise;
}
/**
* Like some(), with 1 as count. However, if the promise fulfills, the
* fulfillment value is not an array of 1 but the value directly.
*
* @template TValue
* @template TReason
*
* @param iterable<TValue|PromiseInterface<TValue, TReason>> $promises Promises or values.
*
* @return PromiseInterface<TValue, \Throwable>
*/
public static function any(iterable $promises): PromiseInterface
{
return self::some(1, $promises)->then(function (array $values) {
return $values[0];
});
}
/**
* Returns a promise that is fulfilled when all of the provided promises
* have been fulfilled or rejected.
*
* The returned promise is fulfilled with an array of inspection state
* arrays.
*
* The config array accepts a concurrency option for lazy iterables. Other
* config keys are ignored by this wrapper.
*
* @see inspect for the inspection state array format.
*
* @template TKey of array-key
* @template TValue
* @template TReason
*
* @param iterable<TKey, TValue|PromiseInterface<TValue, TReason>> $promises Promises or values.
* @param bool $recursive If true, settles newly-added entries until no unprocessed entries or pending promises remain.
* @param array{concurrency?: int|(callable(int): int)} $config Configuration options.
*
* @return PromiseInterface<array<TKey, array{state: PromiseInterface::FULFILLED, value: TValue}|array{state: PromiseInterface::REJECTED, reason: TReason|\Throwable}>, \Throwable>
*/
public static function settle(iterable $promises, bool $recursive = false, array $config = []): PromiseInterface
{
$results = [];
$promise = Each::of(
$promises,
function ($value, $idx) use (&$results): void {
$results[$idx] = ['state' => PromiseInterface::FULFILLED, 'value' => $value];
},
function ($reason, $idx) use (&$results): void {
$results[$idx] = ['state' => PromiseInterface::REJECTED, 'reason' => $reason];
},
$config
)->then(function () use (&$results) {
ksort($results);
return $results;
});
if (true === $recursive) {
$promise = $promise->then(function ($results) use (&$promises, $config) {
if (self::shouldRecurse($promises, $results)) {
return self::settle($promises, true, $config);
}
return $results;
});
}
return $promise;
}
/**
* @template TKey of array-key
*
* @param iterable<TKey, mixed> $promises Promises or values.
* @param array<TKey, mixed> $results Results already collected for a pass.
*/
private static function shouldRecurse(iterable $promises, array $results): bool
{
// A consumed generator cannot be traversed again, so a recursive
// pass has nothing further to observe.
if ($promises instanceof \Generator) {
return false;
}
foreach ($promises as $key => $promise) {
if (!array_key_exists($key, $results)) {
return true;
}
if ($promise instanceof PromiseInterface && Is::pending($promise)) {
return true;
}
}
return false;
}
}