save
This commit is contained in:
Vendored
+62
@@ -0,0 +1,62 @@
|
||||
# Agent Guidelines
|
||||
|
||||
## Code and tooling
|
||||
|
||||
- All code must remain compatible with PHP 7.4. Run PHPStan and PHP-CS-Fixer
|
||||
only under a PHP 7.4.x runtime; never run either tool under any other PHP
|
||||
major.minor version.
|
||||
- Use fully qualified `#[\SensitiveParameter]` on concrete executable
|
||||
parameters when their established role normally carries a secret,
|
||||
credential-bearing aggregate, or confidential Guzzle-owned container, and
|
||||
the active frame can throw or invoke throwing code.
|
||||
- Repeat the attribute on every qualifying owned caller, callee, concrete trait
|
||||
method, and closure parameter. Do not add it to interfaces, abstract-only
|
||||
declarations, pure/no-realistic-throw helpers, assignment-only sites,
|
||||
arbitrary generic payloads, or completed non-recoverable derivatives.
|
||||
- For PHP 7.4 compatibility, put `#[\SensitiveParameter]` on its own line and
|
||||
the parameter on the following line, expand the complete parameter list, and
|
||||
never add a comma after the final parameter. Native trace redaction starts on
|
||||
PHP 8.2 and does not redact logs, messages, properties, wire traffic, captured
|
||||
variables, return values, or the separate backtrace `$this`/`object`.
|
||||
- Always pass an explicit character list to `trim()`, `ltrim()`, and `rtrim()`;
|
||||
never rely on the default characters.
|
||||
- Handle `preg_*` engine failures: when the result is used as data, test for
|
||||
`false` or `null` and throw a `\RuntimeException` including
|
||||
`preg_last_error_msg()`; boolean validation guards must compare strictly, such
|
||||
as `=== 1`, so an engine failure can only ever fail closed. Diagnostic
|
||||
escaping is the narrow exception: use a deterministic bytewise fallback rather
|
||||
than throwing, so it cannot obscure the original exception.
|
||||
- Anchor validation patterns to the true end of input with the `D` modifier or
|
||||
`\z`; a bare `$` accepts a trailing newline.
|
||||
- Never embed raw control bytes in exception messages and other diagnostics;
|
||||
escape or redact the offending value first.
|
||||
- Helper classes that expose only public static methods are `final` and have a
|
||||
private constructor.
|
||||
- Resist native PHP serialization when a class holds live state (streams,
|
||||
resources, handles, callbacks, credentials); plain data holders remain
|
||||
serializable.
|
||||
- To resist, `__serialize()` and `__unserialize()` both throw
|
||||
`\LogicException(static::class.' should never be serialized')` and its
|
||||
unserialized counterpart, via the `@internal` `NonSerializableTrait`.
|
||||
- In general, numeric inputs should not accept non-finite floats. In situations
|
||||
where they are accepted and we need to cast to a string, we should branch on
|
||||
`\is_finite($value)`, using `(string) $value` for the finite case and
|
||||
`\is_nan($value) ? 'NAN' : ($value > 0 ? 'INF' : '-INF')` otherwise.
|
||||
- Never call `strtolower()`, `strtoupper()`, `strcasecmp()`, `stripos()`, or
|
||||
other locale-sensitive case functions; fold ASCII case with
|
||||
`strtr($value, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')`
|
||||
and its inverse instead.
|
||||
- Changes in behavior need a `CHANGELOG.md` entry in the unreleased section of
|
||||
the target branch and an `UPGRADING.md` note when the behavior differs between
|
||||
major versions.
|
||||
|
||||
## Documentation
|
||||
|
||||
- Wrap markdown prose and PHPDoc text to 80 columns using greedy wrapping. Never
|
||||
split a markdown link or an inline code span across a line break; a line that
|
||||
cannot be broken may exceed the limit. Avoid em dashes.
|
||||
- Keep PHPDoc and the corresponding `docs/` pages in sync: shared prose is
|
||||
deliberately word-for-word identical, including boilerplate copied verbatim
|
||||
between related functions, so apply the same edit to every copy. Only
|
||||
formatting and linking may differ, such as a docs link becoming a PHPDoc
|
||||
`@see` tag; the wording must never drift.
|
||||
+303
@@ -0,0 +1,303 @@
|
||||
# CHANGELOG
|
||||
|
||||
|
||||
## 3.2.0 - 2026-11-21
|
||||
|
||||
### Changed
|
||||
|
||||
- Changed `Coroutine` to forward cancellation from chained promises
|
||||
- Changed `TaskQueue` to remove tasks in constant time
|
||||
|
||||
|
||||
## 3.1.2 - 2026-11-21
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed `LogicException` when a callback settles its own promise
|
||||
|
||||
|
||||
## 3.1.1 - 2026-11-19
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed `Promise` losing its handlers when a thenable's `then()` throws
|
||||
- Fixed `Create::promiseFor()` throwing when a thenable's `then()` throws
|
||||
- Fixed quadratic handler forwarding through chains of pending promises
|
||||
- Fixed `Utils::inspect()` losing the outcome of a chained promise
|
||||
|
||||
|
||||
## 3.1.0 - 2026-10-18
|
||||
|
||||
### Added
|
||||
|
||||
- Added `State` promise state checks as a replacement for `Is`
|
||||
|
||||
### Deprecated
|
||||
|
||||
- Deprecated `Is` because PHP 8.6 deprecates `is` as a class name
|
||||
|
||||
|
||||
## 3.0.2 - 2026-08-24
|
||||
|
||||
### Added
|
||||
|
||||
- Added support for PHP 8.6
|
||||
|
||||
|
||||
## 3.0.1 - 2026-08-05
|
||||
|
||||
### Changed
|
||||
|
||||
- Changed the default `TReason` of `FulfilledPromise` and `Create::promiseFor()` to `never`
|
||||
- Changed the default `TValue` of `RejectedPromise` and `Create::rejectionFor()` to `never`
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed `EachPromise` abandoning its aggregate when the pending window drains unsettled
|
||||
- Fixed `EachPromise` admitting new work after its aggregate has settled
|
||||
|
||||
|
||||
## 3.0.0 - 2026-07-20
|
||||
|
||||
### Added
|
||||
|
||||
- Added `concurrency` config support to `Utils::all()` and `Each::of()`
|
||||
- Added generic PHPDoc annotations to promise APIs and collection callbacks
|
||||
- Added recursive and `concurrency` config support to `Utils::settle()`
|
||||
- Allowed promises to be resolved without passing a value
|
||||
|
||||
### Changed
|
||||
|
||||
- Changed `Utils::inspect()` to return actual rejection reasons
|
||||
- Changed `Utils::inspect()` to prefer the settled state over late wait function exceptions
|
||||
- Changed late rejection callbacks to follow rejected promises
|
||||
- Reject native PHP serialization of in-flight runtime objects
|
||||
- Made static helper classes non-instantiable
|
||||
- Require iterable inputs for promise collection helpers and `EachPromise`
|
||||
- Iterate `IteratorAggregate` inputs to collection helpers instead of treating them as a single value
|
||||
- Improved recursive `Utils::all()` handling of dynamically-added settled values and raw values
|
||||
|
||||
### Removed
|
||||
|
||||
- Dropped support for PHP 7.2 and 7.3
|
||||
|
||||
|
||||
## 2.5.1 - 2026-07-08
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed recursive `Utils::all()` rejecting generator inputs
|
||||
|
||||
|
||||
## 2.5.0 - 2026-06-02
|
||||
|
||||
### Deprecated
|
||||
|
||||
- Deprecated passing non-iterable inputs to promise collection helpers and `EachPromise`
|
||||
|
||||
|
||||
## 2.4.1 - 2026-05-20
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed cancelling settled coroutines when no current promise remains
|
||||
|
||||
|
||||
## 2.4.0 - 2026-05-20
|
||||
|
||||
### Changed
|
||||
|
||||
- Empty `EachPromise` instances now resolve when the task queue runs without `wait()`
|
||||
|
||||
|
||||
## 2.3.1 - 2026-05-19
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed `Utils::inspect()` returning the internal reason array instead of the `AggregateException`
|
||||
|
||||
|
||||
## 2.3.0 - 2025-08-22
|
||||
|
||||
### Added
|
||||
|
||||
- PHP 8.5 support
|
||||
|
||||
|
||||
## 2.2.0 - 2025-03-27
|
||||
|
||||
### Fixed
|
||||
|
||||
- Revert "Allow an empty EachPromise to be resolved by running the queue"
|
||||
|
||||
|
||||
## 2.1.0 - 2025-03-27
|
||||
|
||||
### Added
|
||||
|
||||
- Allow an empty EachPromise to be resolved by running the queue
|
||||
|
||||
|
||||
## 2.0.4 - 2024-10-17
|
||||
|
||||
### Fixed
|
||||
|
||||
- Once settled, don't allow further rejection of additional promises
|
||||
|
||||
|
||||
## 2.0.3 - 2024-07-18
|
||||
|
||||
### Changed
|
||||
|
||||
- PHP 8.4 support
|
||||
|
||||
|
||||
## 2.0.2 - 2023-12-03
|
||||
|
||||
### Changed
|
||||
|
||||
- Replaced `call_user_func*` with native calls
|
||||
|
||||
|
||||
## 2.0.1 - 2023-08-03
|
||||
|
||||
### Changed
|
||||
|
||||
- PHP 8.3 support
|
||||
|
||||
|
||||
## 2.0.0 - 2023-05-21
|
||||
|
||||
### Added
|
||||
|
||||
- Added PHP 7 type hints
|
||||
|
||||
### Changed
|
||||
|
||||
- All previously non-final non-exception classes have been marked as soft-final
|
||||
|
||||
### Removed
|
||||
|
||||
- Dropped PHP < 7.2 support
|
||||
- All functions in the `GuzzleHttp\Promise` namespace
|
||||
|
||||
|
||||
## 1.5.3 - 2023-05-21
|
||||
|
||||
### Changed
|
||||
|
||||
- Removed remaining usage of deprecated functions
|
||||
|
||||
|
||||
## 1.5.2 - 2022-08-07
|
||||
|
||||
### Changed
|
||||
|
||||
- Officially support PHP 8.2
|
||||
|
||||
|
||||
## 1.5.1 - 2021-10-22
|
||||
|
||||
### Fixed
|
||||
|
||||
- Revert "Call handler when waiting on fulfilled/rejected Promise"
|
||||
- Fix pool memory leak when empty array of promises provided
|
||||
|
||||
|
||||
## 1.5.0 - 2021-10-07
|
||||
|
||||
### Changed
|
||||
|
||||
- Call handler when waiting on fulfilled/rejected Promise
|
||||
- Officially support PHP 8.1
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fix manually settle promises generated with `Utils::task`
|
||||
|
||||
|
||||
## 1.4.1 - 2021-02-18
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed `each_limit` skipping promises and failing
|
||||
|
||||
|
||||
## 1.4.0 - 2020-09-30
|
||||
|
||||
### Added
|
||||
|
||||
- Support for PHP 8
|
||||
- Optional `$recursive` flag to `all`
|
||||
- Replaced functions by static methods
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fix empty `each` processing
|
||||
- Fix promise handling for Iterators of non-unique keys
|
||||
- Fixed `method_exists` crashes on PHP 8
|
||||
- Memory leak on exceptions
|
||||
|
||||
|
||||
## 1.3.1 - 2016-12-20
|
||||
|
||||
### Fixed
|
||||
|
||||
- `wait()` foreign promise compatibility
|
||||
|
||||
|
||||
## 1.3.0 - 2016-11-18
|
||||
|
||||
### Added
|
||||
|
||||
- Adds support for custom task queues.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed coroutine promise memory leak.
|
||||
|
||||
|
||||
## 1.2.0 - 2016-05-18
|
||||
|
||||
### Changed
|
||||
|
||||
- Update to now catch `\Throwable` on PHP 7+
|
||||
|
||||
|
||||
## 1.1.0 - 2016-03-07
|
||||
|
||||
### Changed
|
||||
|
||||
- Update EachPromise to prevent recurring on a iterator when advancing, as this
|
||||
could trigger fatal generator errors.
|
||||
- Update Promise to allow recursive waiting without unwrapping exceptions.
|
||||
|
||||
|
||||
## 1.0.3 - 2015-10-15
|
||||
|
||||
### Changed
|
||||
|
||||
- Update EachPromise to immediately resolve when the underlying promise iterator
|
||||
is empty. Previously, such a promise would throw an exception when its `wait`
|
||||
function was called.
|
||||
|
||||
|
||||
## 1.0.2 - 2015-05-15
|
||||
|
||||
### Changed
|
||||
|
||||
- Conditionally require functions.php.
|
||||
|
||||
|
||||
## 1.0.1 - 2015-06-24
|
||||
|
||||
### Changed
|
||||
|
||||
- Updating EachPromise to call next on the underlying promise iterator as late
|
||||
as possible to ensure that generators that generate new requests based on
|
||||
callbacks are not iterated until after callbacks are invoked.
|
||||
|
||||
|
||||
## 1.0.0 - 2015-05-12
|
||||
|
||||
- Initial release
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
@AGENTS.md
|
||||
Vendored
+24
@@ -0,0 +1,24 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015 Michael Dowling <mtdowling@gmail.com>
|
||||
Copyright (c) 2015 Graham Campbell <hello@gjcampbell.co.uk>
|
||||
Copyright (c) 2017 Tobias Schultze <webmaster@tubo-world.de>
|
||||
Copyright (c) 2020 Tobias Nyholm <tobias.nyholm@gmail.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
Vendored
+100
@@ -0,0 +1,100 @@
|
||||
# Guzzle Promises
|
||||
|
||||
`guzzlehttp/promises` is a small promise library used by Guzzle for asynchronous
|
||||
operations. It implements promise chaining, synchronous waiting, cancellation,
|
||||
and helpers for working with groups of promises.
|
||||
|
||||
Most application developers use this package through
|
||||
[`guzzlehttp/guzzle`](https://github.com/guzzle/guzzle/blob/8.0/README.md) by
|
||||
calling methods such as `requestAsync()`. Install this package directly when you
|
||||
need promise composition without the full HTTP client.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
composer require guzzlehttp/promises
|
||||
```
|
||||
|
||||
## Version Guidance
|
||||
|
||||
| Version | Status | PHP Version |
|
||||
|---------|--------------|--------------|
|
||||
| 3.2 | Latest | >=7.4,<8.7 |
|
||||
| 2.6 | Maintenance | >=7.2.5,<8.7 |
|
||||
| 1.5 | End of Life | >=5.5,<8.3 |
|
||||
|
||||
## Quick Start
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$promise = new Promise();
|
||||
|
||||
$promise->then(
|
||||
function ($value) {
|
||||
echo 'Fulfilled: ' . $value;
|
||||
},
|
||||
function ($reason) {
|
||||
echo 'Rejected: ' . $reason;
|
||||
}
|
||||
);
|
||||
|
||||
$promise->resolve('done');
|
||||
Utils::queue()->run();
|
||||
```
|
||||
|
||||
You can wait for a promise to complete synchronously:
|
||||
|
||||
```php
|
||||
$value = $promise->wait();
|
||||
```
|
||||
|
||||
A promise's `getState()` describes how it 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 (see
|
||||
[guzzle/promises#101](https://github.com/guzzle/promises/issues/101)).
|
||||
|
||||
When using Guzzle HTTP requests, asynchronous methods return
|
||||
`GuzzleHttp\Promise\PromiseInterface` instances:
|
||||
|
||||
```php
|
||||
$promise = $client->requestAsync('GET', 'https://example.com');
|
||||
$response = $promise->wait();
|
||||
```
|
||||
|
||||
## Documentation
|
||||
|
||||
- [Promise Quick Start](docs/promise-quick-start.md)
|
||||
- [Promise API](docs/promise-api.md)
|
||||
- [Promise Interoperability](docs/promise-interoperability.md)
|
||||
- [Implementation Notes](docs/implementation-notes.md)
|
||||
- [Upgrade Guide](UPGRADING.md)
|
||||
- [Changelog](CHANGELOG.md)
|
||||
|
||||
## Security
|
||||
|
||||
If you discover a security vulnerability within this package, please send an
|
||||
email to security@tidelift.com. All security vulnerabilities will be promptly
|
||||
addressed by the security maintainers listed in the
|
||||
[Security Policy](https://github.com/guzzle/promises/security/policy). Please do
|
||||
not disclose security-related issues publicly until a fix has been announced.
|
||||
|
||||
## License
|
||||
|
||||
Guzzle is made available under the MIT License (MIT). Please see
|
||||
[License File](LICENSE) for more information.
|
||||
|
||||
## For Enterprise
|
||||
|
||||
Available as part of the Tidelift Subscription
|
||||
|
||||
The maintainers of Guzzle and thousands of other packages are working with
|
||||
Tidelift to deliver commercial support and maintenance for the open source
|
||||
dependencies you use to build your applications. Save time, reduce risk, and
|
||||
improve code health, while paying the maintainers of the exact dependencies you
|
||||
use.
|
||||
[Learn more.](https://tidelift.com/subscription/pkg/packagist-guzzlehttp-promises?utm_source=packagist-guzzlehttp-promises&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
|
||||
+279
@@ -0,0 +1,279 @@
|
||||
Guzzle Promises Upgrade Guide
|
||||
=============================
|
||||
|
||||
2.x to 3.0
|
||||
----------
|
||||
|
||||
Guzzle Promises 3.0 is a major release that raises the minimum PHP version,
|
||||
updates promise and collection helper signatures, adds generic PHPDoc types for
|
||||
static analyzers, tightens collection helper inputs, improves recursive
|
||||
collection behavior, and clarifies rejection inspection and late rejection
|
||||
callback behavior.
|
||||
|
||||
#### PHP Version and Dependencies
|
||||
|
||||
Guzzle Promises 3.0 requires PHP `^7.4 || ^8.0`. Guzzle Promises 2.x supported
|
||||
PHP `^7.2.5 || ^8.0`.
|
||||
|
||||
If your application still supports PHP 7.2 or 7.3, continue using Guzzle
|
||||
Promises 2.x until your minimum PHP version is raised.
|
||||
|
||||
Guzzle Promises 3.0 has no runtime package dependencies beyond PHP. It removes
|
||||
the 2.x runtime dependency on `symfony/deprecation-contracts`; require that
|
||||
package directly if your application uses it.
|
||||
|
||||
#### Optional Promise Resolution Values
|
||||
|
||||
`PromiseInterface::resolve()` now accepts an optional value. Calling `resolve()`
|
||||
without an argument fulfills the promise with `null`.
|
||||
|
||||
Custom implementations of `PromiseInterface`, and subclasses that override
|
||||
`resolve()` on `Promise`, `FulfilledPromise`, or `RejectedPromise`, must update
|
||||
their method signature from `resolve($value): void` to
|
||||
`resolve($value = null): void`.
|
||||
|
||||
#### Generic PHPDoc Types
|
||||
|
||||
`PromiseInterface`, `PromisorInterface`, and the built-in promise classes now
|
||||
include generic PHPDoc annotations for static analysis tools. The first template
|
||||
type represents the fulfillment value and the second represents the rejection
|
||||
reason. This is a static-analysis-only change and does not alter runtime
|
||||
behavior, but projects with stricter static analysis may see new or different
|
||||
diagnostics:
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
|
||||
/** @var PromiseInterface<string, \Throwable> */
|
||||
$promise = $factory->createPromise();
|
||||
|
||||
$value = $promise->wait();
|
||||
```
|
||||
|
||||
Code that uses unparameterized promise types continues to work and is treated as
|
||||
`PromiseInterface<mixed, mixed>`. If your project implements promise interfaces,
|
||||
extends promise classes, or has stricter static analysis, you may need to update
|
||||
your PHPDoc annotations to include the generic value and reason types. The
|
||||
expanded PHPDoc also preserves promise-chain fulfillment and rejection types
|
||||
more precisely through `then()` and `otherwise()`, and documents collection
|
||||
callbacks with value or reason, key, and aggregate-promise arguments so
|
||||
callbacks may declare only the arguments they use.
|
||||
|
||||
#### Collection Helper Inputs
|
||||
|
||||
Promise collection helpers now require iterable inputs. Passing a single promise
|
||||
or scalar value directly now throws a `TypeError`.
|
||||
|
||||
Wrap single promises or values in an array before passing them to
|
||||
`Create::iterFor()`, `Each::of()`, `Each::ofLimit()`, `Each::ofLimitAll()`,
|
||||
`EachPromise`, or the `Utils` collection helpers.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Each;
|
||||
|
||||
// 2.x
|
||||
$promise = Each::ofLimit($singlePromise, 2);
|
||||
|
||||
// 3.0
|
||||
$promise = Each::ofLimit([$singlePromise], 2);
|
||||
```
|
||||
|
||||
`IteratorAggregate` inputs are now iterated via `getIterator()`. In 2.x an
|
||||
aggregate was treated as a single value and produced one result; in 3.0 its
|
||||
entries are consumed individually.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$aggregate = new \ArrayObject([$promiseA, $promiseB]);
|
||||
|
||||
// 2.x: one result — the ArrayObject itself
|
||||
// 3.0: two results — the fulfillment values of $promiseA and $promiseB
|
||||
$promise = Utils::all($aggregate);
|
||||
```
|
||||
|
||||
#### Collection Helper Signatures
|
||||
|
||||
`Utils::all()`, `Utils::settle()`, and `Each::of()` now accept trailing optional
|
||||
arguments. Direct calls using the 2.x argument lists continue to work, and the
|
||||
affected helper classes are final so subclass signatures do not need to change.
|
||||
Code that mirrors or reflects exact helper signatures may need to be updated.
|
||||
|
||||
Pass the recursive flag before the config array when using `Utils::all()` or
|
||||
`Utils::settle()`:
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$promise = Utils::all($promises, false, ['concurrency' => 5]);
|
||||
$promise = Utils::settle($promises, false, ['concurrency' => 5]);
|
||||
```
|
||||
|
||||
Only `concurrency` is honored by these helper config arrays. Callback config
|
||||
keys such as `fulfilled` and `rejected` are ignored; pass callbacks to
|
||||
`Each::of()` directly or use `EachPromise`.
|
||||
|
||||
#### Recursive Collection Helpers
|
||||
|
||||
Existing `Utils::all($promises, true)` calls may return different results in
|
||||
3.0. Recursive mode now detects dynamically-added settled promises and raw
|
||||
values. In 2.x, recursive mode only checked for pending promises.
|
||||
|
||||
If you previously worked around the lack of recursive `Utils::settle()` support,
|
||||
you can replace that workaround with the new `$recursive` argument:
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$promise = Utils::settle($promises, true);
|
||||
```
|
||||
|
||||
When `$recursive` is true, collection helpers continue taking passes over the
|
||||
collection until no new entries are found and no visible promises remain
|
||||
pending. This is intended for rewindable mutable collections such as
|
||||
`ArrayIterator`. Generators are safe to pass, but they cannot be traversed
|
||||
again once consumed, so recursive mode degrades to a single pass; use a
|
||||
rewindable mutable collection when recursion needs to observe added values.
|
||||
|
||||
#### Promise Inspection
|
||||
|
||||
`Utils::inspect()` and `Utils::inspectAll()` now return the actual rejection
|
||||
reason delivered to rejection callbacks. They no longer unwrap
|
||||
`RejectionException` instances to their inner reason.
|
||||
|
||||
For example, a promise rejected with a `RejectionException` now inspects with
|
||||
that exception as the reason:
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\RejectedPromise;
|
||||
use GuzzleHttp\Promise\RejectionException;
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$reason = new RejectionException('reason');
|
||||
$result = Utils::inspect(new RejectedPromise($reason));
|
||||
|
||||
assert($result['reason'] === $reason);
|
||||
```
|
||||
|
||||
Cancelled promises now inspect with a `CancellationException` reason. If you
|
||||
need the string reason from a `RejectionException` or subclass, call
|
||||
`getReason()` on the exception.
|
||||
|
||||
`Utils::inspect()` still reports wait-function failures as rejection reasons
|
||||
when the wait function does not settle the promise. If the wait function
|
||||
settles the promise and then throws, `inspect()` reports the settled
|
||||
fulfillment or rejection state; direct `Promise::wait()` calls continue to
|
||||
throw that late exception.
|
||||
|
||||
#### Late Rejection Callbacks
|
||||
|
||||
Rejection callbacks registered after a promise was resolved with a rejected
|
||||
promise are now invoked with the nested rejection reason.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
use GuzzleHttp\Promise\RejectedPromise;
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$promise = new Promise();
|
||||
$promise->resolve(new RejectedPromise('reason'));
|
||||
|
||||
$promise->then(null, function ($reason): void {
|
||||
assert($reason === 'reason');
|
||||
});
|
||||
|
||||
Utils::queue()->run();
|
||||
```
|
||||
|
||||
#### Non-instantiable Helper Classes
|
||||
|
||||
Static helper classes such as `Create`, `Each`, `Is`, and `Utils` now have
|
||||
private constructors. Replace any accidental instantiation with static method
|
||||
calls.
|
||||
|
||||
#### Native PHP Serialization of Runtime Objects
|
||||
|
||||
`Promise`, `TaskQueue`, `EachPromise`, and `Coroutine` no longer support native
|
||||
PHP `serialize()` or `unserialize()`. Persist application values instead of
|
||||
promise runtime state.
|
||||
|
||||
1.x to 2.0
|
||||
----------
|
||||
|
||||
Guzzle Promises 2.0 is a major release that removes deprecated APIs, raises the
|
||||
minimum PHP version, and adds PHP 7 parameter and return types. Applications that
|
||||
only use the object-oriented API should usually need small changes. Applications
|
||||
that call helper functions, implement package interfaces, extend package classes,
|
||||
or pass invalid argument types need closer review.
|
||||
|
||||
#### PHP Version and Dependencies
|
||||
|
||||
Guzzle Promises 2.0 requires PHP `^7.2.5 || ^8.0`. Guzzle Promises 1.x
|
||||
supported PHP `>=5.5`.
|
||||
|
||||
#### PHP 7 Type Hints and Return Types
|
||||
|
||||
Type hints and return types were added wherever possible. Please make sure:
|
||||
|
||||
- You pass values of the documented type when calling methods and functions.
|
||||
- Classes that implement `PromiseInterface`, `PromisorInterface`, or
|
||||
`TaskQueueInterface` update method signatures to remain compatible.
|
||||
- Classes that extend Guzzle Promises classes update any overridden method
|
||||
signatures to remain compatible.
|
||||
- Code that expected package-specific exceptions for invalid argument types may
|
||||
now receive PHP `TypeError` exceptions instead.
|
||||
|
||||
#### Soft-Final Classes
|
||||
|
||||
All previously non-final non-exception classes are now final or annotated with
|
||||
`@final`. If your code extends one of these classes, replace inheritance with
|
||||
composition or implement the relevant interface directly.
|
||||
|
||||
#### Removed Function API
|
||||
|
||||
The static API was introduced in 1.4.0 to mitigate problems with functions
|
||||
conflicting between global and local copies of the package. The function API was
|
||||
removed in 2.0.0, along with the Composer `files` autoload entry that loaded
|
||||
`src/functions_include.php`.
|
||||
|
||||
Replace namespaced function calls with the corresponding static methods in the
|
||||
`GuzzleHttp\Promise` namespace:
|
||||
|
||||
```php
|
||||
// Before:
|
||||
use function GuzzleHttp\Promise\promise_for;
|
||||
|
||||
$promise = promise_for('value');
|
||||
|
||||
// After:
|
||||
use GuzzleHttp\Promise\Create;
|
||||
|
||||
$promise = Create::promiseFor('value');
|
||||
```
|
||||
|
||||
| Original Function | Replacement Method |
|
||||
|-------------------|--------------------|
|
||||
| `queue` | `Utils::queue` |
|
||||
| `task` | `Utils::task` |
|
||||
| `promise_for` | `Create::promiseFor` |
|
||||
| `rejection_for` | `Create::rejectionFor` |
|
||||
| `exception_for` | `Create::exceptionFor` |
|
||||
| `iter_for` | `Create::iterFor` |
|
||||
| `inspect` | `Utils::inspect` |
|
||||
| `inspect_all` | `Utils::inspectAll` |
|
||||
| `unwrap` | `Utils::unwrap` |
|
||||
| `all` | `Utils::all` |
|
||||
| `some` | `Utils::some` |
|
||||
| `any` | `Utils::any` |
|
||||
| `settle` | `Utils::settle` |
|
||||
| `each` | `Each::of` |
|
||||
| `each_limit` | `Each::ofLimit` |
|
||||
| `each_limit_all` | `Each::ofLimitAll` |
|
||||
| `!is_fulfilled` | `Is::pending` |
|
||||
| `is_fulfilled` | `Is::fulfilled` |
|
||||
| `is_rejected` | `Is::rejected` |
|
||||
| `is_settled` | `Is::settled` |
|
||||
| `coroutine` | `Coroutine::of` |
|
||||
|
||||
For the full 2.0 diff, see
|
||||
https://github.com/guzzle/promises/compare/1.5.3...2.0.0.
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"name": "guzzlehttp/promises",
|
||||
"description": "Guzzle promises library",
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"promise"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Graham Campbell",
|
||||
"email": "hello@gjcampbell.co.uk",
|
||||
"homepage": "https://github.com/GrahamCampbell"
|
||||
},
|
||||
{
|
||||
"name": "Michael Dowling",
|
||||
"email": "mtdowling@gmail.com",
|
||||
"homepage": "https://github.com/mtdowling"
|
||||
},
|
||||
{
|
||||
"name": "Tobias Nyholm",
|
||||
"email": "tobias.nyholm@gmail.com",
|
||||
"homepage": "https://github.com/Nyholm"
|
||||
},
|
||||
{
|
||||
"name": "Tobias Schultze",
|
||||
"email": "webmaster@tubo-world.de",
|
||||
"homepage": "https://github.com/Tobion"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": "^7.4 || ^8.0",
|
||||
"symfony/deprecation-contracts": "^2.5 || ^3.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"bamarni/composer-bin-plugin": "^1.8.2",
|
||||
"phpunit/phpunit": "^9.6.34"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"GuzzleHttp\\Promise\\": "src/"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"GuzzleHttp\\Promise\\Tests\\": "tests/"
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"allow-plugins": {
|
||||
"bamarni/composer-bin-plugin": true
|
||||
},
|
||||
"preferred-install": "dist",
|
||||
"sort-packages": true
|
||||
},
|
||||
"extra": {
|
||||
"bamarni-bin": {
|
||||
"bin-links": true,
|
||||
"forward-command": false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
# Implementation Notes
|
||||
|
||||
This document describes implementation details that explain observable behavior
|
||||
in `guzzlehttp/promises`, especially queue-based callback execution, iterative
|
||||
resolution, and why `Promise` also acts as the deferred value. Application code
|
||||
usually only needs the [Promise Quick Start](promise-quick-start.md) and
|
||||
[Promise API](promise-api.md).
|
||||
|
||||
## Iterative Resolution and Chaining
|
||||
|
||||
Promises are resolved iteratively by moving pending handlers between promises.
|
||||
This keeps stack size constant even for very long `then()` chains.
|
||||
|
||||
```php
|
||||
<?php
|
||||
require 'vendor/autoload.php';
|
||||
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
|
||||
$parent = new Promise();
|
||||
$p = $parent;
|
||||
|
||||
for ($i = 0; $i < 1000; $i++) {
|
||||
$p = $p->then(function ($v) {
|
||||
// The stack size remains constant.
|
||||
echo xdebug_get_stack_depth() . ', ';
|
||||
return $v + 1;
|
||||
});
|
||||
}
|
||||
|
||||
$parent->resolve(0);
|
||||
var_dump($p->wait()); // int(1000)
|
||||
|
||||
```
|
||||
|
||||
When a promise is fulfilled or rejected with a non-promise value, the promise
|
||||
takes ownership of each child promise's handlers and delivers values down the
|
||||
chain without recursion.
|
||||
|
||||
When a promise is resolved with another promise, the original promise transfers
|
||||
all of its pending handlers to the new promise. When the new promise is
|
||||
eventually resolved, all pending handlers receive the forwarded
|
||||
value.
|
||||
|
||||
## A Promise Is the Deferred
|
||||
|
||||
Some promise libraries implement promises using a deferred object to represent
|
||||
a computation and a promise object to represent the delivery of the result of
|
||||
the computation. That separation prevents consumers from modifying the value
|
||||
that will eventually be delivered.
|
||||
|
||||
Iterative resolution requires one promise to move handlers from another promise.
|
||||
To do that without making handlers publicly mutable, `Promise` is also the
|
||||
deferred value. Promises of the same class can modify each other's private
|
||||
state, including handler ownership. This means a consumer that receives a
|
||||
`Promise` can also resolve or reject it, but it keeps chaining efficient and
|
||||
stack safe.
|
||||
|
||||
```php
|
||||
$promise = new Promise();
|
||||
$promise->then(function ($value) { echo $value; });
|
||||
// The promise is the deferred value, so you can deliver a value to it.
|
||||
$promise->resolve('foo');
|
||||
GuzzleHttp\Promise\Utils::queue()->run();
|
||||
// Prints "foo"
|
||||
```
|
||||
|
||||
## Related
|
||||
|
||||
- [Quick Start](promise-quick-start.md)
|
||||
- [Promise API](promise-api.md)
|
||||
- [Promise Interoperability](promise-interoperability.md)
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
# Promise API
|
||||
|
||||
This reference summarizes the public API provided by `guzzlehttp/promises`.
|
||||
Promise APIs are documented for static analysis as
|
||||
`PromiseInterface<TValue, TReason>`. `TValue` is the fulfillment value type and
|
||||
`TReason` is the rejection reason type. This typing is PHPDoc-only and does not
|
||||
change runtime behavior.
|
||||
|
||||
Callbacks registered with `then()` are queued. They are invoked when the global
|
||||
task queue runs, when a returned promise is waited on, or when the queue is
|
||||
drained by the default shutdown handler.
|
||||
|
||||
## PromiseInterface and Promise
|
||||
|
||||
`PromiseInterface` defines the common promise contract and the states
|
||||
`pending`, `fulfilled`, and `rejected`.
|
||||
|
||||
When creating a `Promise`, you can provide an optional `$waitFn` and
|
||||
`$cancelFn`. `$waitFn` receives a boolean argument and is expected to resolve or
|
||||
reject the promise. `$cancelFn` receives no arguments and is invoked when
|
||||
`cancel()` is called.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
|
||||
$promise = new Promise(
|
||||
function (bool $recursive) use (&$promise) {
|
||||
$promise->resolve('waited');
|
||||
},
|
||||
function () {
|
||||
// Cancel the underlying operation, such as closing a socket.
|
||||
}
|
||||
);
|
||||
|
||||
assert('waited' === $promise->wait());
|
||||
```
|
||||
|
||||
A promise has the following methods:
|
||||
|
||||
- `then(?callable $onFulfilled = null, ?callable $onRejected = null) : PromiseInterface` appends fulfillment and rejection handlers and returns a new promise resolving to the return value of the called handler. If a handler is omitted, the original fulfillment value or rejection reason is forwarded.
|
||||
- `otherwise(callable $onRejected) : PromiseInterface` appends a rejection handler and returns a new promise resolving to the callback result if called, or to the original fulfillment value if the promise is fulfilled.
|
||||
- `wait(bool $unwrap = true) : mixed` synchronously waits on the promise. When `$unwrap` is `true`, fulfilled values are returned and rejected reasons are thrown. When `$unwrap` is `false`, the promise is settled without returning or throwing its result.
|
||||
- `cancel() : void` attempts to cancel the promise and dependent promises.
|
||||
- `getState() : string` returns `pending`, `fulfilled`, or `rejected`.
|
||||
- `resolve($value = null) : void` fulfills the promise with `$value`, or with `null` if no value is given.
|
||||
- `reject($reason) : void` rejects the promise with `$reason`.
|
||||
|
||||
## Settled Promises
|
||||
|
||||
`FulfilledPromise` represents an already fulfilled promise. Fulfillment
|
||||
callbacks are still queued and run when the task queue runs or the returned
|
||||
promise is waited on.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\FulfilledPromise;
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$promise = new FulfilledPromise('value');
|
||||
$promise->then(function ($value) {
|
||||
echo $value;
|
||||
});
|
||||
|
||||
Utils::queue()->run();
|
||||
```
|
||||
|
||||
`RejectedPromise` represents an already rejected promise. Rejection callbacks
|
||||
are also queued and run when the queue is drained or the returned promise is
|
||||
waited on.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\RejectedPromise;
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$promise = new RejectedPromise('Error');
|
||||
$promise->then(null, function ($reason) {
|
||||
echo $reason;
|
||||
});
|
||||
|
||||
Utils::queue()->run();
|
||||
```
|
||||
|
||||
## Utils
|
||||
|
||||
`GuzzleHttp\Promise\Utils` provides helpers for inspecting, aggregating, and
|
||||
queuing promise work.
|
||||
|
||||
- `Utils::queue(?TaskQueueInterface $assign = null) : TaskQueueInterface` returns the global task queue, or assigns a replacement queue when `$assign` is provided.
|
||||
- `Utils::task(callable $task) : PromiseInterface` adds a task to the global queue and returns a promise that is fulfilled or rejected with the task result.
|
||||
- `Utils::inspect(PromiseInterface $promise) : array` waits for one promise to settle and returns an inspection array with `state` and either `value` or `reason`.
|
||||
- `Utils::inspectAll(iterable $promises) : array` inspects each promise and returns inspection arrays keyed like the input iterable.
|
||||
- `Utils::unwrap(iterable $promises) : array` waits on all promises and returns fulfilled values, throwing if any promise rejects.
|
||||
- `Utils::all(iterable $promises, bool $recursive = false, array $config = []) : PromiseInterface` returns a promise fulfilled with all values, or rejected when any input rejects.
|
||||
- `Utils::settle(iterable $promises, bool $recursive = false, array $config = []) : PromiseInterface` returns a promise fulfilled with inspection arrays after all inputs settle.
|
||||
- `Utils::some(int $count, iterable $promises) : PromiseInterface` fulfills with the values of the first `$count` promises to fulfill, in the order they appear in the input, or rejects with `AggregateException` if too few fulfill.
|
||||
- `Utils::any(iterable $promises) : PromiseInterface` fulfills with the first fulfilled value, or rejects with `AggregateException` if none fulfill.
|
||||
|
||||
`Utils::all()` and `Utils::settle()` accept `['concurrency' => 5]` or
|
||||
`['concurrency' => callable]` for lazy iterables. This limits how many items are
|
||||
pulled from the iterable at one time; it does not throttle promises that have
|
||||
already been created or started.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$promise = Utils::all($promises, false, ['concurrency' => 5]);
|
||||
```
|
||||
|
||||
## Create
|
||||
|
||||
`GuzzleHttp\Promise\Create` provides factories used by the promise
|
||||
implementation and by callers that need to normalize values.
|
||||
|
||||
- `Create::promiseFor($value) : PromiseInterface` returns `$value` when it is already a Guzzle promise, wraps foreign thenables in a Guzzle promise, or returns a fulfilled promise for plain values.
|
||||
- `Create::rejectionFor($reason) : PromiseInterface` returns `$reason` when it is already a promise, or returns a rejected promise for plain reasons.
|
||||
- `Create::exceptionFor($reason) : Throwable` returns throwable reasons as-is, or wraps non-throwable reasons in `RejectionException`.
|
||||
- `Create::iterFor(iterable $value) : Iterator` returns an iterator for arrays, iterators, iterator aggregates, and traversables.
|
||||
|
||||
## State
|
||||
|
||||
`GuzzleHttp\Promise\State` provides readable state checks:
|
||||
|
||||
- `State::isPending(PromiseInterface $promise) : bool`
|
||||
- `State::isSettled(PromiseInterface $promise) : bool`
|
||||
- `State::isFulfilled(PromiseInterface $promise) : bool`
|
||||
- `State::isRejected(PromiseInterface $promise) : bool`
|
||||
|
||||
`GuzzleHttp\Promise\Is` is deprecated because PHP 8.6 deprecates `is` as a class
|
||||
name, and will be removed in Guzzle Promises 4.0. Replace `Is::pending()`,
|
||||
`Is::settled()`, `Is::fulfilled()`, and `Is::rejected()` with the matching
|
||||
`State` methods.
|
||||
|
||||
## Each and EachPromise
|
||||
|
||||
`Each::of()` consumes an iterable of promises or values and invokes callbacks as
|
||||
items settle. Fulfillment callbacks receive the fulfilled value, iterable key,
|
||||
and aggregate promise. Rejection callbacks receive the rejection reason,
|
||||
iterable key, and aggregate promise. Callback return values are ignored.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Each;
|
||||
|
||||
$promise = Each::of($promises, $onFulfilled, $onRejected, ['concurrency' => 5]);
|
||||
```
|
||||
|
||||
- `Each::of(iterable $iterable, ?callable $onFulfilled = null, ?callable $onRejected = null, array $config = []) : PromiseInterface` consumes the iterable and optionally limits lazy iteration with `concurrency`.
|
||||
- `Each::ofLimit(iterable $iterable, $concurrency, ?callable $onFulfilled = null, ?callable $onRejected = null) : PromiseInterface` is a convenience wrapper for `Each::of()` with a concurrency limit.
|
||||
- `Each::ofLimitAll(iterable $iterable, $concurrency, ?callable $onFulfilled = null) : PromiseInterface` is like `ofLimit()`, but rejects the aggregate promise on the first rejection.
|
||||
- `EachPromise` is the configurable class behind `Each`; use it directly when you need `fulfilled`, `rejected`, and `concurrency` keys in one configuration array.
|
||||
|
||||
The concurrency options limit lazy promise creation. For HTTP request
|
||||
concurrency, use `GuzzleHttp\Pool` from `guzzlehttp/guzzle`.
|
||||
|
||||
## Coroutine
|
||||
|
||||
`Coroutine::of(callable $generatorFn) : Coroutine` creates a promise resolved by
|
||||
a generator that yields values or promises. The generator resumes with each
|
||||
fulfilled value, and rejections are thrown into the generator.
|
||||
|
||||
## Task Queue
|
||||
|
||||
`TaskQueueInterface` exposes `isEmpty()`, `add(callable $task)`, and `run()`.
|
||||
`TaskQueue` executes queued tasks in FIFO order. The default queue runs at
|
||||
process shutdown unless disabled, and `wait()` drains the queue while resolving
|
||||
the promise being waited on.
|
||||
|
||||
## Exceptions
|
||||
|
||||
- `RejectionException` is thrown by `wait()` when a rejected promise has a non-throwable reason. The original reason is available through `getReason()`.
|
||||
- `AggregateException` extends `RejectionException` and is used by `Utils::some()` and `Utils::any()` when too few promises fulfill.
|
||||
- `CancellationException` extends `RejectionException` and is used as the rejection reason for cancelled promises.
|
||||
|
||||
## Related
|
||||
|
||||
- [Quick Start](promise-quick-start.md)
|
||||
- [Promise Interoperability](promise-interoperability.md)
|
||||
- [Implementation Notes](implementation-notes.md)
|
||||
- [Upgrade Guide](../UPGRADING.md)
|
||||
@@ -0,0 +1,78 @@
|
||||
# Promise Interoperability
|
||||
|
||||
This guide explains how Guzzle promises interact with foreign promise
|
||||
implementations. A foreign promise is any object with a `then` method, such as a
|
||||
[React promise](https://github.com/reactphp/promise). When a foreign promise is
|
||||
returned from a `then` callback, Guzzle forwards resolution to that promise.
|
||||
|
||||
## Foreign Promises
|
||||
|
||||
Capture the promise returned from `then()`. That chained promise is the Guzzle
|
||||
promise that follows the foreign promise's eventual result.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$deferred = new React\Promise\Deferred();
|
||||
$reactPromise = $deferred->promise();
|
||||
|
||||
$guzzlePromise = new Promise();
|
||||
$chained = $guzzlePromise->then(function ($value) use ($reactPromise) {
|
||||
// Use the Guzzle value, then continue with the React promise.
|
||||
return $reactPromise;
|
||||
});
|
||||
|
||||
$chained->then(function ($value) {
|
||||
echo $value;
|
||||
});
|
||||
|
||||
$guzzlePromise->resolve('start');
|
||||
Utils::queue()->run();
|
||||
|
||||
$deferred->resolve('done');
|
||||
Utils::queue()->run();
|
||||
```
|
||||
|
||||
Forwarding a foreign promise does not make Guzzle able to synchronously wait on
|
||||
or cancel the foreign operation. The chained Guzzle promise settles only after
|
||||
the foreign implementation invokes the callbacks registered through `then()`.
|
||||
If the foreign promise has no compatible `wait()` or `cancel()` behavior, Guzzle
|
||||
cannot invent that behavior.
|
||||
|
||||
Use `Create::promiseFor($foreignPromise)` to shadow a foreign thenable as a
|
||||
Guzzle promise. If the foreign object exposes `wait()` or `cancel()` methods,
|
||||
the wrapper uses them. Otherwise, use the foreign implementation's event loop or
|
||||
completion mechanism and drain Guzzle's task queue when callbacks need to run.
|
||||
|
||||
## Event Loop Integration
|
||||
|
||||
Guzzle promises use a task queue to keep stack size constant and to run promise
|
||||
callbacks asynchronously. When waiting on promises synchronously, the task queue
|
||||
is automatically run while resolving the blocking promise and forwarded Guzzle
|
||||
promises.
|
||||
|
||||
When using promises asynchronously in an event loop, run the task queue on loop
|
||||
ticks. If you do not run the task queue, Guzzle promise callbacks may remain
|
||||
queued.
|
||||
|
||||
```php
|
||||
$queue = GuzzleHttp\Promise\Utils::queue();
|
||||
$queue->run();
|
||||
```
|
||||
|
||||
For example, you could use Guzzle promises with React using a short periodic
|
||||
timer. Avoid zero-interval timers because they may keep the loop busy even when
|
||||
there is no promise work to run.
|
||||
|
||||
```php
|
||||
$queue = GuzzleHttp\Promise\Utils::queue();
|
||||
$loop = React\EventLoop\Factory::create();
|
||||
$loop->addPeriodicTimer(0.01, [$queue, 'run']);
|
||||
```
|
||||
|
||||
## Related
|
||||
|
||||
- [Quick Start](promise-quick-start.md)
|
||||
- [Promise API](promise-api.md)
|
||||
- [Implementation Notes](implementation-notes.md)
|
||||
@@ -0,0 +1,319 @@
|
||||
# Promise Quick Start
|
||||
|
||||
This guide covers the common promise operations needed when using
|
||||
`guzzlehttp/promises` directly: registering callbacks, resolving or rejecting
|
||||
promises, waiting synchronously, composing chains, and using generator-based
|
||||
flows. For the full public surface, see the [Promise API](promise-api.md).
|
||||
|
||||
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 the eventual value or the reason why the
|
||||
promise cannot be fulfilled.
|
||||
|
||||
Guzzle promise callbacks are queued. They run when the task queue is drained,
|
||||
for example by `Utils::queue()->run()`, by waiting on a returned promise, or by
|
||||
the default shutdown handler at the end of the PHP process. Examples that show
|
||||
callback output drain the queue explicitly.
|
||||
|
||||
## Callbacks
|
||||
|
||||
Callbacks are registered with the `then` method by providing an optional
|
||||
`$onFulfilled` followed by an optional `$onRejected` function.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
|
||||
$promise = new Promise();
|
||||
$promise->then(
|
||||
// $onFulfilled
|
||||
function ($value) {
|
||||
echo 'The promise was fulfilled.';
|
||||
},
|
||||
// $onRejected
|
||||
function ($reason) {
|
||||
echo 'The promise was rejected.';
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
*Resolving* a promise means that you either fulfill a promise with a *value* or
|
||||
reject a promise with a *reason*. Callbacks registered with `then` are invoked
|
||||
only once and in the order in which they were added when the queue is drained.
|
||||
|
||||
## Resolving a Promise
|
||||
|
||||
Promises are fulfilled using the `resolve($value = null)` method. Calling
|
||||
`resolve()` without an argument fulfills the promise with `null`. Resolving a
|
||||
promise with any value other than a `GuzzleHttp\Promise\RejectedPromise` queues
|
||||
the `$onFulfilled` callbacks. Resolving with a rejected promise rejects the
|
||||
promise and queues the `$onRejected` callbacks.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$promise = new Promise();
|
||||
$promise
|
||||
->then(function ($value) {
|
||||
return 'Hello, ' . $value;
|
||||
})
|
||||
->then(function ($value) {
|
||||
echo $value;
|
||||
});
|
||||
|
||||
$promise->resolve('reader.');
|
||||
Utils::queue()->run();
|
||||
// Outputs "Hello, reader."
|
||||
```
|
||||
|
||||
## Promise Forwarding
|
||||
|
||||
Promises can be chained one after the other. Each `then` call returns a new
|
||||
promise. The return value of a callback is forwarded to the next promise in the
|
||||
chain. Returning a promise from a callback makes the next promise wait for that
|
||||
returned promise to settle.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$promise = new Promise();
|
||||
$nextPromise = new Promise();
|
||||
|
||||
$promise
|
||||
->then(function ($value) use ($nextPromise) {
|
||||
echo $value;
|
||||
|
||||
return $nextPromise;
|
||||
})
|
||||
->then(function ($value) {
|
||||
echo $value;
|
||||
});
|
||||
|
||||
$promise->resolve('A');
|
||||
Utils::queue()->run();
|
||||
// Outputs "A"
|
||||
|
||||
$nextPromise->resolve('B');
|
||||
Utils::queue()->run();
|
||||
// Outputs "B"
|
||||
```
|
||||
|
||||
## Promise Rejection
|
||||
|
||||
When a promise is rejected, the `$onRejected` callbacks are invoked with the
|
||||
rejection reason when the queue is drained.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$promise = new Promise();
|
||||
$promise->then(null, function ($reason) {
|
||||
echo $reason;
|
||||
});
|
||||
|
||||
$promise->reject('Error!');
|
||||
Utils::queue()->run();
|
||||
// Outputs "Error!"
|
||||
```
|
||||
|
||||
## Rejection Forwarding
|
||||
|
||||
If an exception is thrown in an `$onRejected` callback, subsequent
|
||||
`$onRejected` callbacks receive the thrown exception as the reason.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$promise = new Promise();
|
||||
$promise->then(null, function ($reason) {
|
||||
throw new Exception($reason);
|
||||
})->then(null, function ($reason) {
|
||||
assert($reason->getMessage() === 'Error!');
|
||||
});
|
||||
|
||||
$promise->reject('Error!');
|
||||
Utils::queue()->run();
|
||||
```
|
||||
|
||||
You can also forward a rejection down the promise chain by returning a
|
||||
`GuzzleHttp\Promise\RejectedPromise` in either an `$onFulfilled` or
|
||||
`$onRejected` callback.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
use GuzzleHttp\Promise\RejectedPromise;
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$promise = new Promise();
|
||||
$promise->then(null, function ($reason) {
|
||||
return new RejectedPromise($reason);
|
||||
})->then(null, function ($reason) {
|
||||
assert($reason === 'Error!');
|
||||
});
|
||||
|
||||
$promise->reject('Error!');
|
||||
Utils::queue()->run();
|
||||
```
|
||||
|
||||
If an exception is not thrown in an `$onRejected` callback and the callback
|
||||
does not return a rejected promise, downstream `$onFulfilled` callbacks are
|
||||
invoked using the value returned from the `$onRejected` callback.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
use GuzzleHttp\Promise\Utils;
|
||||
|
||||
$promise = new Promise();
|
||||
$promise
|
||||
->then(null, function ($reason) {
|
||||
return "It's ok";
|
||||
})
|
||||
->then(function ($value) {
|
||||
assert($value === "It's ok");
|
||||
});
|
||||
|
||||
$promise->reject('Error!');
|
||||
Utils::queue()->run();
|
||||
```
|
||||
|
||||
## Synchronous Wait
|
||||
|
||||
You can synchronously force promises to complete using a promise's `wait`
|
||||
method. When creating a promise, you can provide a wait function that is used
|
||||
to synchronously complete the promise. The wait function receives a boolean
|
||||
argument and is expected to resolve or reject the promise. If the wait function
|
||||
does not settle the promise, an exception is thrown.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
|
||||
$promise = new Promise(function (bool $recursive) use (&$promise) {
|
||||
$promise->resolve('foo');
|
||||
});
|
||||
|
||||
echo $promise->wait();
|
||||
// Outputs "foo"
|
||||
```
|
||||
|
||||
If a throwable is encountered while invoking the wait function of a promise,
|
||||
the promise is rejected with the throwable and the throwable is thrown.
|
||||
|
||||
```php
|
||||
$promise = new Promise(function (bool $recursive) use (&$promise) {
|
||||
throw new Exception('foo');
|
||||
});
|
||||
|
||||
$promise->wait(); // Throws the exception.
|
||||
```
|
||||
|
||||
Calling `wait` on a promise that has been fulfilled will not trigger the wait
|
||||
function. It will simply return the previously resolved value.
|
||||
|
||||
```php
|
||||
$promise = new Promise(function (bool $recursive) { die('this is not called!'); });
|
||||
$promise->resolve('foo');
|
||||
|
||||
echo $promise->wait();
|
||||
// Outputs "foo"
|
||||
```
|
||||
|
||||
Calling `wait` on a promise that has been rejected will throw. If the rejection
|
||||
reason is an instance of `\Throwable`, the reason is thrown. Otherwise, a
|
||||
`GuzzleHttp\Promise\RejectionException` is thrown and the reason can be
|
||||
obtained by calling `getReason()` on the exception.
|
||||
|
||||
```php
|
||||
$promise = new Promise();
|
||||
$promise->reject('foo');
|
||||
$promise->wait();
|
||||
```
|
||||
|
||||
> PHP Fatal error: Uncaught exception 'GuzzleHttp\Promise\RejectionException' with message 'The promise was rejected with reason: foo'
|
||||
|
||||
## Unwrapping a Promise
|
||||
|
||||
When synchronously waiting on a promise, you are joining the state of the
|
||||
promise into the current execution: the fulfilled value is returned, or the
|
||||
rejection reason is thrown. This is called "unwrapping" the promise. Waiting on
|
||||
a promise unwraps by default.
|
||||
|
||||
You can force a promise to resolve and *not* unwrap its state by passing
|
||||
`false` to `wait()`:
|
||||
|
||||
```php
|
||||
$promise = new Promise();
|
||||
$promise->reject('foo');
|
||||
|
||||
// This does not throw. It only ensures the promise has been resolved.
|
||||
$promise->wait(false);
|
||||
```
|
||||
|
||||
When unwrapping a promise, the resolved value of the promise will be waited on
|
||||
until the unwrapped value is not a promise. This means that if promise A is
|
||||
resolved with promise B, unwrapping promise A returns the value delivered to
|
||||
promise B.
|
||||
|
||||
When you do not unwrap the promise, no value is returned.
|
||||
|
||||
## Inspecting a Promise
|
||||
|
||||
`Utils::inspect($promise)` waits for a promise to settle and returns an array
|
||||
describing its final state. For rejected promises, the `reason` entry is the
|
||||
actual rejection reason delivered to rejection callbacks.
|
||||
|
||||
This means `RejectionException` and subclasses are not unwrapped by
|
||||
`inspect()`. For example, cancelled promises inspect with a
|
||||
`CancellationException` reason.
|
||||
|
||||
## Generator-Based Async
|
||||
|
||||
`Coroutine::of()` creates a promise from a generator that yields values or
|
||||
promises. The generator resumes each time the yielded value settles, which can
|
||||
make sequential asynchronous flows easier to read.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Coroutine;
|
||||
use GuzzleHttp\Promise\FulfilledPromise;
|
||||
|
||||
$promise = Coroutine::of(function () {
|
||||
$first = yield new FulfilledPromise('A');
|
||||
$second = yield new FulfilledPromise($first . 'B');
|
||||
|
||||
yield $second . 'C';
|
||||
});
|
||||
|
||||
echo $promise->wait();
|
||||
// Outputs "ABC"
|
||||
```
|
||||
|
||||
If a yielded promise rejects, the rejection is thrown into the generator. Catch
|
||||
it inside the generator to recover, or let it reject the coroutine promise.
|
||||
|
||||
## Cancellation
|
||||
|
||||
You can cancel a promise that has not yet been fulfilled using `cancel()`. When
|
||||
creating a promise, you can provide an optional cancel function that cancels the
|
||||
underlying operation, such as closing a socket or aborting a query.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
|
||||
$promise = new Promise(null, function () {
|
||||
// Cancel the underlying operation.
|
||||
});
|
||||
|
||||
$promise->cancel();
|
||||
```
|
||||
|
||||
Cancellation rejects the promise with a `CancellationException` unless the
|
||||
cancel function settles the promise first.
|
||||
|
||||
## Related
|
||||
|
||||
- [Promise API](promise-api.md)
|
||||
- [Promise Interoperability](promise-interoperability.md)
|
||||
- [Implementation Notes](implementation-notes.md)
|
||||
- [Upgrade Guide](../UPGRADING.md)
|
||||
@@ -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))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
}
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
<?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();
|
||||
}
|
||||
}, function (): void {
|
||||
if (isset($this->currentPromise)) {
|
||||
$this->currentPromise->cancel();
|
||||
}
|
||||
});
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
<?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);
|
||||
try {
|
||||
$value->then([$promise, 'resolve'], [$promise, 'reject']);
|
||||
} catch (\Throwable $e) {
|
||||
if (State::isPending($promise)) {
|
||||
// The thenable may still hold the callbacks.
|
||||
$promise = new Promise();
|
||||
$promise->reject($e);
|
||||
}
|
||||
}
|
||||
|
||||
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
@@ -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);
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
+295
@@ -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 || State::isSettled($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 (State::isSettled($this->aggregate)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Refill and re-sweep; give up only when nothing remains.
|
||||
$this->refillPending();
|
||||
if (State::isSettled($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 (State::isSettled($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 (!State::isSettled($this->aggregate)) {
|
||||
$this->checkIfFinished();
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private function step(int $idx): void
|
||||
{
|
||||
// If the promise was already resolved, then ignore this step.
|
||||
if (State::isSettled($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;
|
||||
}
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
<?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 {
|
||||
try {
|
||||
if (State::isPending($p)) {
|
||||
$p->resolve($onFulfilled($value));
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
if (State::isPending($p)) {
|
||||
$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
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Promise;
|
||||
|
||||
/**
|
||||
* @deprecated Is will be removed in guzzlehttp/promises:4.0. Use State instead.
|
||||
*/
|
||||
final class Is
|
||||
{
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if a promise is pending.
|
||||
*
|
||||
* @deprecated Is::pending() will be removed in guzzlehttp/promises:4.0. Use
|
||||
* State::isPending() instead.
|
||||
*/
|
||||
public static function pending(PromiseInterface $promise): bool
|
||||
{
|
||||
\trigger_deprecation(
|
||||
'guzzlehttp/promises',
|
||||
'3.1',
|
||||
'%s() is deprecated and will be removed in 4.0. Use %s::isPending() instead.',
|
||||
__METHOD__,
|
||||
State::class
|
||||
);
|
||||
|
||||
return State::isPending($promise);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if a promise is fulfilled or rejected.
|
||||
*
|
||||
* @deprecated Is::settled() will be removed in guzzlehttp/promises:4.0. Use
|
||||
* State::isSettled() instead.
|
||||
*/
|
||||
public static function settled(PromiseInterface $promise): bool
|
||||
{
|
||||
\trigger_deprecation(
|
||||
'guzzlehttp/promises',
|
||||
'3.1',
|
||||
'%s() is deprecated and will be removed in 4.0. Use %s::isSettled() instead.',
|
||||
__METHOD__,
|
||||
State::class
|
||||
);
|
||||
|
||||
return State::isSettled($promise);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if a promise is fulfilled.
|
||||
*
|
||||
* @deprecated Is::fulfilled() will be removed in guzzlehttp/promises:4.0.
|
||||
* Use State::isFulfilled() instead.
|
||||
*/
|
||||
public static function fulfilled(PromiseInterface $promise): bool
|
||||
{
|
||||
\trigger_deprecation(
|
||||
'guzzlehttp/promises',
|
||||
'3.1',
|
||||
'%s() is deprecated and will be removed in 4.0. Use %s::isFulfilled() instead.',
|
||||
__METHOD__,
|
||||
State::class
|
||||
);
|
||||
|
||||
return State::isFulfilled($promise);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if a promise is rejected.
|
||||
*
|
||||
* @deprecated Is::rejected() will be removed in guzzlehttp/promises:4.0.
|
||||
* Use State::isRejected() instead.
|
||||
*/
|
||||
public static function rejected(PromiseInterface $promise): bool
|
||||
{
|
||||
\trigger_deprecation(
|
||||
'guzzlehttp/promises',
|
||||
'3.1',
|
||||
'%s() is deprecated and will be removed in 4.0. Use %s::isRejected() instead.',
|
||||
__METHOD__,
|
||||
State::class
|
||||
);
|
||||
|
||||
return State::isRejected($promise);
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
+358
@@ -0,0 +1,358 @@
|
||||
<?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 $handlersBefore = [];
|
||||
|
||||
/** @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;
|
||||
$before = $this->handlersBefore;
|
||||
$this->handlers = $this->handlersBefore = null;
|
||||
$this->waitList = $this->waitFn = null;
|
||||
$this->cancelFn = null;
|
||||
|
||||
if (!$handlers) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($value instanceof Promise && State::isPending($value)) {
|
||||
// We can just hand our handlers to the next promise. Merging would
|
||||
// copy both lists every time, so only the shorter one is moved.
|
||||
if ($value->handlers === []) {
|
||||
$value->handlers = $handlers;
|
||||
$value->handlersBefore = $before;
|
||||
} elseif (count($value->handlers) + count($value->handlersBefore) < count($handlers) + count($before)) {
|
||||
array_push($before, ...array_reverse($value->handlers), ...$value->handlersBefore);
|
||||
$value->handlers = $handlers;
|
||||
$value->handlersBefore = $before;
|
||||
} else {
|
||||
array_push($value->handlers, ...array_reverse($before), ...$handlers);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($before) {
|
||||
$handlers = array_merge(array_reverse($before), $handlers);
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// Resolve the handlers when the forwarded promise is resolved.
|
||||
try {
|
||||
$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);
|
||||
}
|
||||
}
|
||||
);
|
||||
} catch (\Throwable $e) {
|
||||
Utils::queue()->add(static function () use ($e, $handlers): void {
|
||||
foreach ($handlers as $handler) {
|
||||
self::callHandler(2, $e, $handler);
|
||||
}
|
||||
});
|
||||
// The thenable may still hold the callbacks.
|
||||
$handlers = [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 (State::isSettled($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) {
|
||||
// The handler may have settled the promise itself.
|
||||
if (State::isPending($promise)) {
|
||||
$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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+119
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
<?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 {
|
||||
try {
|
||||
if (State::isPending($p)) {
|
||||
// Return a resolved promise if onRejected does not throw.
|
||||
$p->resolve($onRejected($reason));
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
// onRejected threw, so return a rejected promise.
|
||||
if (State::isPending($p)) {
|
||||
$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
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace GuzzleHttp\Promise;
|
||||
|
||||
final class State
|
||||
{
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if a promise is pending.
|
||||
*/
|
||||
public static function isPending(PromiseInterface $promise): bool
|
||||
{
|
||||
return $promise->getState() === PromiseInterface::PENDING;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if a promise is fulfilled or rejected.
|
||||
*/
|
||||
public static function isSettled(PromiseInterface $promise): bool
|
||||
{
|
||||
return $promise->getState() !== PromiseInterface::PENDING;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if a promise is fulfilled.
|
||||
*/
|
||||
public static function isFulfilled(PromiseInterface $promise): bool
|
||||
{
|
||||
return $promise->getState() === PromiseInterface::FULFILLED;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if a promise is rejected.
|
||||
*/
|
||||
public static function isRejected(PromiseInterface $promise): bool
|
||||
{
|
||||
return $promise->getState() === PromiseInterface::REJECTED;
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
<?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 \SplQueue<callable(): void> */
|
||||
private \SplQueue $queue;
|
||||
|
||||
public function __construct(bool $withShutdown = true)
|
||||
{
|
||||
$this->queue = new \SplQueue();
|
||||
|
||||
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 __clone()
|
||||
{
|
||||
$this->queue = clone $this->queue;
|
||||
}
|
||||
|
||||
public function isEmpty(): bool
|
||||
{
|
||||
return $this->queue->isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param callable(): void $task
|
||||
*/
|
||||
public function add(callable $task): void
|
||||
{
|
||||
$this->queue->enqueue($task);
|
||||
}
|
||||
|
||||
public function run(): void
|
||||
{
|
||||
while (!$this->queue->isEmpty()) {
|
||||
$task = $this->queue->dequeue();
|
||||
$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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
+385
@@ -0,0 +1,385 @@
|
||||
<?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 (State::isPending($promise)) {
|
||||
$promise->resolve($task());
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
if (State::isPending($promise)) {
|
||||
$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;
|
||||
}
|
||||
|
||||
try {
|
||||
self::queue()->run();
|
||||
} catch (\Throwable $queueError) {
|
||||
return ['state' => PromiseInterface::REJECTED, 'reason' => $queueError];
|
||||
}
|
||||
|
||||
return $getResult() ?? ['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 (State::isPending($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 (State::isSettled($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 && State::isPending($promise)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user