diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml
index ddb6fe4..ccd69bf 100644
--- a/.github/workflows/ci.yaml
+++ b/.github/workflows/ci.yaml
@@ -17,7 +17,7 @@ jobs:
- name: "Setup PHP"
uses: shivammathur/setup-php@v2
with:
- php-version: 8.2
+ php-version: 8.5
coverage: none
- name: "Install dependencies"
@@ -38,7 +38,7 @@ jobs:
- name: "Setup PHP"
uses: shivammathur/setup-php@v2
with:
- php-version: 8.2
+ php-version: 8.5
coverage: none
- name: "Install dependencies"
@@ -55,7 +55,7 @@ jobs:
strategy:
fail-fast: false
matrix:
- php-version: [ '8.2', '8.3' ]
+ php-version: [ '8.2', '8.3', '8.4', '8.5' ]
prefer-lowest: ['', '--prefer-lowest --prefer-stable']
coverage-driver: [ 'xdebug' ]
diff --git a/.gitignore b/.gitignore
index 29cca22..5e9e7da 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,5 @@
.php-cs-fixer.cache
+.phpunit.cache
.phpunit.result.cache
phpunit.xml
composer.lock
diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php
index 8384c26..9cc1763 100644
--- a/.php-cs-fixer.dist.php
+++ b/.php-cs-fixer.dist.php
@@ -12,13 +12,12 @@
return (new PhpCsFixer\Config())
->setRiskyAllowed(true)
+ // the tools run on the newest PHP; the migration rule sets below keep the code at the PHP 8.2 floor
+ ->setUnsupportedPhpVersionAllowed(true)
->setRules([
'@Symfony' => true,
- '@PHP80Migration' => true,
- '@PHP80Migration:risky' => true,
- '@PHP81Migration' => true,
- '@PHP82Migration' => true,
- '@PHP83Migration' => true,
+ '@PHP8x2Migration:risky' => true,
+ '@PHP8x2Migration' => true,
'php_unit_method_casing' => false,
'php_unit_test_case_static_method_calls' => ['call_type' => 'self'],
])
diff --git a/.phpstan/baseline.neon b/.phpstan/baseline.neon
index 364905f..aab4991 100644
--- a/.phpstan/baseline.neon
+++ b/.phpstan/baseline.neon
@@ -1,2 +1,2 @@
parameters:
- ignoreErrors:
+ ignoreErrors: []
diff --git a/.phpstan/config.neon b/.phpstan/config.neon
index 740a2d5..9690b17 100644
--- a/.phpstan/config.neon
+++ b/.phpstan/config.neon
@@ -7,7 +7,6 @@ parameters:
level: max
- checkMissingIterableValueType: false
reportUnmatchedIgnoredErrors: true
treatPhpDocTypesAsCertain: false
diff --git a/Makefile b/Makefile
index 8538064..e31fc91 100644
--- a/Makefile
+++ b/Makefile
@@ -36,11 +36,11 @@ qa: cs-check analyse
.PHONY: cs-check
cs-check:
- XDEBUG_MODE=off PHP_CS_FIXER_FUTURE_MODE=1 PHP_CS_FIXER_IGNORE_ENV=1 $(PHP_CS_FIXER_BIN) fix --allow-risky=yes --diff --using-cache=no --verbose --dry-run
+ XDEBUG_MODE=off PHP_CS_FIXER_FUTURE_MODE=1 $(PHP_CS_FIXER_BIN) fix --allow-risky=yes --diff --using-cache=no --verbose --dry-run
.PHONY: cs-fix
cs-fix:
- XDEBUG_MODE=off PHP_CS_FIXER_FUTURE_MODE=1 PHP_CS_FIXER_IGNORE_ENV=1 $(PHP_CS_FIXER_BIN) fix --allow-risky=yes
+ XDEBUG_MODE=off PHP_CS_FIXER_FUTURE_MODE=1 $(PHP_CS_FIXER_BIN) fix --allow-risky=yes
.PHONY: analyse
analyse:
diff --git a/README.md b/README.md
index 509456f..ba727ff 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,7 @@
-
+
@@ -58,39 +58,189 @@ composer require jschaedl/api-client
## Examples
-...
+Runnable examples live in [`examples/`](examples) (Shopware 5/6, MobilePay, a generic request).
+
+```php
+use Api\Client;
+use Api\Request\Encoder\JsonRequestBodyEncoder;
+use Api\Request\Handler\AddHeaderHandler;
+use Api\Request\Method;
+use Api\Request\Request;
+use Api\Response\Decoder\JsonResponseBodyDecoder;
+use Symfony\Component\HttpClient\HttpClient;
+use Symfony\Component\HttpClient\Psr18Client;
+
+// timeouts belong to the PSR-18 client: PSR-18 has no per-request options
+$psr18 = new Psr18Client(HttpClient::create(['timeout' => 10, 'max_duration' => 30]));
+
+$client = new Client(
+ $psr18, $psr18, $psr18,
+ 'https://api.example.com/v1',
+ requestHandler: new AddHeaderHandler('Authorization', 'Bearer '.$token),
+ requestBodyEncoder: new JsonRequestBodyEncoder(),
+ responseBodyDecoder: new JsonResponseBodyDecoder(),
+);
+
+$response = $client->request(new Request(Method::POST, 'orders', ['sku' => 'ABC-1']));
+$response->statusCode(); // 201
+$response->body(); // ['id' => 42, ...]
+```
+
+---
## Features
### Client
-### GenericRequest and Response
+`Client` turns a `RequestInterface` into a PSR-7 request, sends it with any PSR-18 client and
+returns a `ResponseInterface`. Request URIs are relative to the base URI.
+
+### Request and Response
+
+`Request` carries method, URI, body and headers. The body is
+
+- an **array**: encoded by the request's own encoder, or the client's (see below);
+- a **string**: sent exactly as it is (binary uploads, pre-encoded payloads);
+- **null**: no body.
+
+`Response` keeps the raw body (`rawBody()`) and decodes it lazily on the first `body()` call, so a
+PDF download or an HTML error page is never run through a JSON decoder unless you ask for it.
+`header('retry-after')` looks a header up case-insensitively.
+
+### Error handling
+
+By default the client throws on every 4xx/5xx response. All exceptions implement
+`Api\Exception\ApiExceptionInterface`:
+
+| Exception | When | `getCode()` |
+| --- | --- | --- |
+| `ClientException` | 4xx response | HTTP status |
+| `ServerException` | 5xx response | HTTP status |
+| `TransportException` | no complete response (DNS, connect, TLS, timeout, broken body) | 0 |
+| `DecodingException` | `body()` cannot decode the response | HTTP status |
+
+Messages name the method and path only (`HTTP 422 returned for "POST members".`). They never contain
+the response body (error responses often echo personal data back) or the query string (some APIs
+take credentials there). The request, the response and the original exception stay reachable via
+`request()`, `response()` and `getPrevious()`.
+
+Pass `throwOnErrorStatus: false` to get error responses returned instead.
### Request and Response Handlers
+Request handlers change a request before it is sent (`AddHeaderHandler`, `AddAccessTokenHandler`,
+`ChainRequestHandler`). Response handlers see every response **before** the status check, so they
+can turn an expected error into a domain exception:
+
+```php
+final class MemberNotFoundHandler implements ResponseHandlerInterface
+{
+ public function handle(ResponseInterface $response, RequestInterface $request): ResponseInterface
+ {
+ if (404 === $response->statusCode()) {
+ throw new MemberNotFound();
+ }
+
+ return $response;
+ }
+}
+```
+
### Request/Response Body Encoder/Decoder
+`JsonRequestBodyEncoder` and `FormRequestBodyEncoder` (`application/x-www-form-urlencoded`) set
+their own `Content-Type`; a header set on the request wins. A request can bring its own encoder,
+e.g. a form-encoded OAuth token call on an otherwise JSON API:
+
+```php
+new Request(Method::POST, 'oauth/token', ['grant_type' => 'client_credentials'], bodyEncoder: new FormRequestBodyEncoder());
+```
+
### Custom Requests and Responses
+Extend `Request`, or implement `RequestInterface` with the `IsGet`, `IsPost`, `IsPut`, `IsPatch`
+and `IsDelete` traits. See `examples/shopware6.php` for typed request and response classes.
+
### RetryClient
+`RetryClient` decorates any `ClientInterface` and sends a failed request again when its
+`RetryStrategyInterface` allows it. `GenericRetryStrategy` retries only what was provably not
+processed, or what is safe to repeat. A POST that failed with a 5xx or a timeout may have been
+processed anyway, and resending it can create a second order or invoice. The defaults:
+
+| Failure | GET, HEAD, OPTIONS, PUT, DELETE | POST, PATCH |
+| --- | --- | --- |
+| 429 Too Many Requests | retried | retried (rate limiters reject before processing) |
+| 423, 425, 500, 502, 503, 504 | retried | not retried |
+| Network error (timeout, DNS, connection reset) | retried | not retried |
+| Any other status | not retried | not retried |
+
+Delays grow exponentially with jitter and are capped. `Retry-After` (seconds or HTTP-date) is
+honoured; if it asks for longer than `maxDelay`, the request is not retried. `maxDuration` bounds
+the whole sequence, waits included.
+
+```php
+use Api\RetryClient;
+use Api\Retry\GenericRetryStrategy;
+
+$client = new RetryClient(
+ $client,
+ new GenericRetryStrategy(
+ statusCodes: [409 => GenericRetryStrategy::IDEMPOTENT_METHODS, 429], // codes with methods = only those methods
+ delay: 20.0, // seconds before the first retry
+ multiplier: 1.0, // flat: one retry per rate-limit window
+ maxDelay: 20.0,
+ ),
+ maxRetries: 3,
+ maxDuration: 70.0,
+);
+```
+
### Testing with Mocks
+`Api\Testing\MockClient` answers requests from a queue and records them, which is handy for
+testing code that uses a client. Error responses are thrown as `ResponseException`, like the real client
+does:
+
+```php
+$client = new MockClient([
+ MockClient::json(['id' => 7]),
+ MockClient::json(['error' => 'not found'], 404),
+]);
+
+// ... exercise your code ...
+
+self::assertCount(2, $client->requests());
+```
+
+`Api\Clock\MockClock` advances its time on `sleep()` instead of waiting. Pass it to `RetryClient`
+and `GenericRetryStrategy` to test retries without delays; `sleeps()` returns the waits.
+
+To test the `Client` itself without network access, wrap Symfony's `MockHttpClient` in a
+`Psr18Client`.
+
---
## FAQ
**How can I add custom headers to requests?**
-...
+Globally with `AddHeaderHandler` (combine several with `ChainRequestHandler`), or per request with
+`$request->addHeader('X-Foo', 'bar')`. Request headers win.
**How can I send authentication information along with a request?**
-...
+Use `AddAccessTokenHandler` with your own `AccessTokenProviderInterface` (see
+`examples/shopware6.php` for a cached client-credentials token), or `AddHeaderHandler` for static
+keys.
+
+**How can I use a Client in my tests?**
+
+See [Testing with Mocks](#testing-with-mocks).
-**How can use a Client in my tests?**
+**How do I upgrade from 0.0.1?**
-...
+See [UPGRADE-0.1.md](UPGRADE-0.1.md).
---
diff --git a/UPGRADE-0.1.md b/UPGRADE-0.1.md
new file mode 100644
index 0000000..f0adf2c
--- /dev/null
+++ b/UPGRADE-0.1.md
@@ -0,0 +1,61 @@
+# Upgrade from 0.0.1 to 0.1.0
+
+0.1.0 supports PHP 8.2 to 8.5 and reworks retries and error handling. These changes need action.
+
+## Requirements
+
+- PHP 8.2 to 8.5.
+- `psr/http-factory` 1.1 or newer (1.0 declares implicitly nullable parameters, which PHP 8.4
+ deprecates).
+- `psr/clock` is a new dependency.
+
+## Errors are thrown by default
+
+`Client` now throws on every 4xx/5xx response: `ClientException` / `ServerException`, both
+extending `ResponseException`. Network failures throw `TransportException` instead of the PSR-18
+exception. Every exception implements `Api\Exception\ApiExceptionInterface`.
+
+- To keep getting error responses returned, pass `throwOnErrorStatus: false`.
+- `ResponseException` (and its subclasses) are now built from the request and response:
+ `new ClientException($request, $response)` replaces `new ClientException(404, 'Not Found')`.
+ `getCode()` is the HTTP status.
+
+## Retries
+
+`RetryTrait` is gone. `RetryClient` takes a `RetryStrategyInterface`:
+
+```php
+// 0.0.1
+new RetryClient($client, 3, true);
+
+// 0.1.0
+new RetryClient($client, new GenericRetryStrategy(), maxRetries: 3);
+```
+
+Behaviour changes:
+
+- 5xx and network failures are retried for **idempotent methods only**. 0.0.1 retried a 5xx for
+ every method, POST included.
+- 429 is retried for every method. `Retry-After` is honoured.
+- `maxRetries` now counts retries: `maxRetries: 3` means up to 4 requests. 0.0.1 counted attempts.
+- Waiting goes through `Api\Clock\ClockInterface`; use `MockClock` in tests instead of overriding
+ `getWaitTimeFactor()`.
+
+## Request bodies
+
+- `RequestInterface::body()` returns `array|string|null`. A string is sent as it is.
+- `RequestBodyEncoderInterface` gained `contentType()`. The client sets that `Content-Type` unless
+ the request sets the header itself, so `AddHeaderHandler('Content-Type', 'application/json')`
+ is no longer needed.
+- `JsonRequestBodyEncoder` no longer escapes slashes and unicode by default. Pass flags to the
+ constructor for the old output: `new JsonRequestBodyEncoder(0)`.
+
+## Responses
+
+- `ResponseInterface` gained `rawBody()` and `header()`; custom implementations must add them.
+- The body is decoded lazily on the first `body()` call. Decoding errors throw
+ `DecodingException` there, not inside `Client::request()`.
+- `ResponseBodyDecoderInterface::decode()` returns `mixed`. `JsonResponseBodyDecoder` no longer
+ casts the result to an array.
+- `ResponseHandlerInterface::handle()` receives the request as a second argument and works on
+ `ResponseInterface` instead of `Response`. Handlers now run before the status check.
diff --git a/composer.json b/composer.json
index 2a19822..b18456b 100644
--- a/composer.json
+++ b/composer.json
@@ -20,35 +20,39 @@
"psr-4": {
"Api\\": "src/Api"
},
- "files": ["examples/_function.php"]
+ "files": [
+ "examples/_function.php"
+ ]
},
"config": {
"sort-packages": true
},
"require": {
- "php": "~8.2||~8.3",
- "psr/http-client": "^1",
- "psr/http-factory": "^1",
- "webmozart/assert": "^1"
+ "php": "~8.2.0||~8.3.0||~8.4.0||~8.5.0",
+ "psr/clock": "^1.0",
+ "psr/http-client": "^1.0",
+ "psr/http-factory": "^1.1",
+ "psr/http-message": "^1.1||^2.0",
+ "webmozart/assert": "^1.11"
},
"require-dev": {
- "azjezz/psl": "^2.9",
- "brianium/paratest": "^6.11",
- "friendsofphp/php-cs-fixer": "^3.49.0",
- "guzzlehttp/guzzle": "^7.8.1",
- "guzzlehttp/psr7": "^2.6.2",
- "nyholm/psr7": "^1.8.1",
- "phpstan/phpstan": "^1.10.58",
- "phpstan/phpstan-phpunit": "^1.3.15",
- "phpunit/phpunit": "^9.6.16",
- "rector/rector": "^0.14.8",
- "spatie/phpunit-snapshot-assertions": "^4.2.16",
- "symfony/http-client": "^6.4.3",
- "symplify/phpstan-rules": "^11.4.1.72",
- "tomasvotruba/cognitive-complexity": "^0.0.1",
- "tomasvotruba/type-coverage": "^0.0.1"
+ "brianium/paratest": "^7.8.5",
+ "friendsofphp/php-cs-fixer": "^3.75",
+ "guzzlehttp/guzzle": "^7.9",
+ "guzzlehttp/psr7": "^2.7",
+ "nyholm/psr7": "^1.8.2",
+ "phpstan/phpstan": "^2.1",
+ "phpstan/phpstan-phpunit": "^2.0",
+ "phpunit/phpunit": "^11.5",
+ "rector/rector": "^2.0",
+ "symfony/http-client": "^6.4||^7.0",
+ "tomasvotruba/cognitive-complexity": "^1.0",
+ "tomasvotruba/type-coverage": "^2.0"
},
"provide": {
"php-http/client-implementation": "*"
+ },
+ "suggest": {
+ "symfony/http-client": "PSR-18 client (Psr18Client) that also implements the PSR-17 factories"
}
}
diff --git a/examples/generic-request.php b/examples/generic-request.php
index b8cf56b..712dcb3 100644
--- a/examples/generic-request.php
+++ b/examples/generic-request.php
@@ -23,7 +23,6 @@
$request = new Request(Method::POST, '/echo/post/json');
$request
->addHeader('Accept', 'application/json')
- ->addHeader('Content-Type', 'application/json')
->setBody(['json' => true])
;
@@ -32,6 +31,6 @@
var_dump($response->statusCode());
var_dump($response->body());
-} catch (Exception $exception) {
+} catch (Api\Exception\ApiExceptionInterface $exception) {
var_dump($exception->getMessage());
}
diff --git a/examples/mobilepay.php b/examples/mobilepay.php
index aaa97f9..67f093b 100644
--- a/examples/mobilepay.php
+++ b/examples/mobilepay.php
@@ -60,7 +60,6 @@ public static function fromResponse(ResponseInterface $response): self
getEnvVarValue('MOBILEPAY_API_HOST'),
requestHandler: new ChainRequestHandler([
new AddHeaderHandler('Accept', 'application/json'),
- new AddHeaderHandler('Content-Type', 'application/json'),
new AddHeaderHandler('Authorization', getEnvVarValue('MOBILEPAY_API_KEY')),
]),
requestBodyEncoder: $requestBodyEncoder,
diff --git a/examples/shopware5.php b/examples/shopware5.php
index 27ec4ac..bd8166f 100644
--- a/examples/shopware5.php
+++ b/examples/shopware5.php
@@ -15,7 +15,6 @@
getEnvVarValue('SHOPWARE5_API_HOST'),
requestHandler: new Api\Request\Handler\ChainRequestHandler([
new Api\Request\Handler\AddHeaderHandler('Accept', 'application/json'),
- new Api\Request\Handler\AddHeaderHandler('Content-Type', 'application/json'),
new Api\Request\Handler\AddHeaderHandler(
'Authorization',
'Basic'.base64_encode(sprintf('%s:%s', getEnvVarValue('SHOPWARE5_API_USER'), getEnvVarValue('SHOPWARE5_API_KEY')))
diff --git a/examples/shopware6.php b/examples/shopware6.php
index a08777e..c758050 100644
--- a/examples/shopware6.php
+++ b/examples/shopware6.php
@@ -14,11 +14,7 @@
use Api\Request\Request;
use Api\Response\Decoder\JsonResponseBodyDecoder;
use Api\Response\ResponseInterface;
-use Psl\Type\TypeInterface;
use Symfony\Component\HttpClient\Psr18Client;
-use function Psl\Type\positive_int;
-use function Psl\Type\shape;
-use function Psl\Type\string;
require_once __DIR__.'/../vendor/autoload.php';
@@ -47,22 +43,17 @@ public function __construct(
public static function fromResponse(ResponseInterface $response): self
{
- $body = self::type()->coerce($response->body());
-
- return new self(
- $body['token_type'],
- $body['expires_in'],
- $body['access_token'],
- );
- }
+ $body = $response->body();
+
+ if (!is_array($body)
+ || !is_string($body['token_type'] ?? null)
+ || !is_int($body['expires_in'] ?? null) || $body['expires_in'] < 1
+ || !is_string($body['access_token'] ?? null)
+ ) {
+ throw new UnexpectedValueException('Unexpected access token response.');
+ }
- private static function type(): TypeInterface
- {
- return shape([
- 'token_type' => string(),
- 'expires_in' => positive_int(),
- 'access_token' => string(),
- ], true);
+ return new self($body['token_type'], $body['expires_in'], $body['access_token']);
}
}
@@ -106,7 +97,6 @@ public function provideToken(): AccessToken
getEnvVarValue('SHOPWARE6_API_HOST'),
requestHandler: new ChainRequestHandler([
new AddHeaderHandler('Accept', 'application/json'),
- new AddHeaderHandler('Content-Type', 'application/json'),
]),
requestBodyEncoder: $requestBodyEncoder,
responseBodyDecoder: $responseBodyDecoder,
@@ -125,7 +115,6 @@ public function provideToken(): AccessToken
getEnvVarValue('SHOPWARE6_API_HOST'),
requestHandler: new ChainRequestHandler([
new AddHeaderHandler('Accept', 'application/json'),
- new AddHeaderHandler('Content-Type', 'application/json'),
new AddAccessTokenHandler($accessTokenProvider, 'Authorization'),
]),
requestBodyEncoder: $requestBodyEncoder,
diff --git a/phpstan.neon b/phpstan.neon
index 2064ef4..53962c0 100644
--- a/phpstan.neon
+++ b/phpstan.neon
@@ -12,7 +12,8 @@ parameters:
function: 12
type_coverage:
- return_type: 78
- param_type: 84
- property_type: 20
- print_suggestions: false
+ return_type: 99
+ param_type: 99
+ property_type: 99
+ # typed class constants need PHP 8.3; raise once PHP 8.2 support is dropped
+ constant_type: 0
diff --git a/phpunit.xml.dist b/phpunit.xml.dist
index 964e11f..e141429 100644
--- a/phpunit.xml.dist
+++ b/phpunit.xml.dist
@@ -1,24 +1,27 @@
-
+ failOnDeprecation="true"
+ failOnPhpunitDeprecation="true"
+ displayDetailsOnTestsThatTriggerDeprecations="true"
+ displayDetailsOnPhpunitDeprecations="true"
+ colors="true">
+
src/
src/
-
+
src
diff --git a/rector.php b/rector.php
index ad289d9..479c57d 100644
--- a/rector.php
+++ b/rector.php
@@ -4,7 +4,6 @@
use Rector\CodeQuality\Rector\Class_\InlineConstructorDefaultToPropertyRector;
use Rector\Config\RectorConfig;
-use Rector\PHPUnit\Rector\Class_\AddSeeTestAnnotationRector;
use Rector\Set\ValueObject\LevelSetList;
use Rector\Set\ValueObject\SetList;
@@ -22,10 +21,9 @@
$rectorConfig->rules([
InlineConstructorDefaultToPropertyRector::class,
- AddSeeTestAnnotationRector::class,
]);
$rectorConfig->sets([
- LevelSetList::UP_TO_PHP_81,
+ LevelSetList::UP_TO_PHP_82,
SetList::CODE_QUALITY,
SetList::DEAD_CODE,
SetList::EARLY_RETURN,
diff --git a/src/Api/Client.php b/src/Api/Client.php
index 532d4ea..95c7f1f 100644
--- a/src/Api/Client.php
+++ b/src/Api/Client.php
@@ -4,6 +4,9 @@
namespace Api;
+use Api\Exception\ResponseException;
+use Api\Exception\TransportException;
+use Api\Request\BodyEncoderAwareRequestInterface;
use Api\Request\HeadersAwareRequestInterface;
use Api\Request\RequestBodyEncoderInterface;
use Api\Request\RequestHandlerInterface;
@@ -12,77 +15,102 @@
use Api\Response\ResponseBodyDecoderInterface;
use Api\Response\ResponseHandlerInterface;
use Api\Response\ResponseInterface;
+use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Client\ClientInterface as PsrClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
+use Psr\Http\Message\RequestInterface as Psr7RequestInterface;
use Psr\Http\Message\StreamFactoryInterface;
-final class Client implements ClientInterface
+/**
+ * Timeouts are a property of the PSR-18 client you pass in (PSR-18 has no per-request
+ * options): configure them there, e.g. `new Psr18Client(HttpClient::create(['timeout' => 10]))`.
+ *
+ * @see ClientTest
+ */
+final readonly class Client implements ClientInterface
{
public function __construct(
- private readonly PsrClientInterface $httpClient,
- private readonly RequestFactoryInterface $requestFactory,
- private readonly StreamFactoryInterface $streamFactory,
- private readonly string $baseUri,
- private readonly ?RequestHandlerInterface $requestHandler = null,
- private readonly ?ResponseHandlerInterface $responseHandler = null,
- private readonly ?RequestBodyEncoderInterface $requestBodyEncoder = null,
- private readonly ?ResponseBodyDecoderInterface $responseBodyDecoder = null,
+ private PsrClientInterface $httpClient,
+ private RequestFactoryInterface $requestFactory,
+ private StreamFactoryInterface $streamFactory,
+ private string $baseUri,
+ private ?RequestHandlerInterface $requestHandler = null,
+ private ?ResponseHandlerInterface $responseHandler = null,
+ private ?RequestBodyEncoderInterface $requestBodyEncoder = null,
+ private ?ResponseBodyDecoderInterface $responseBodyDecoder = null,
+ private bool $throwOnErrorStatus = true,
) {
}
public function request(RequestInterface $request): ResponseInterface
{
- // execute request handler
- if ($this->requestHandler) {
+ if ($this->requestHandler instanceof RequestHandlerInterface) {
$request = $this->requestHandler->handle($request);
}
- $baseUri = rtrim($this->baseUri, '/');
- $requestUri = ltrim($request->uri(), '/');
+ $psr7Request = $this->createPsr7Request($request);
- // create psr7 request
- $psr7Request = $this->requestFactory->createRequest($request->method(), $baseUri.'/'.$requestUri);
+ try {
+ $psr7Response = $this->httpClient->sendRequest($psr7Request);
+ // the body may break off mid-read, which is a transport failure as well
+ $rawBody = (string) $psr7Response->getBody();
+ } catch (ClientExceptionInterface|\RuntimeException $exception) {
+ throw new TransportException($request, $exception);
+ }
+
+ $headers = [];
+ foreach ($psr7Response->getHeaders() as $name => $values) {
+ $headers[(string) $name] = array_values($values);
+ }
+
+ $response = new Response($rawBody, $psr7Response->getStatusCode(), $headers, $this->responseBodyDecoder);
- $requestBody = $request->body();
+ if ($this->responseHandler instanceof ResponseHandlerInterface) {
+ $response = $this->responseHandler->handle($response, $request);
+ }
- if ($requestBody && !$this->requestBodyEncoder) {
- throw new \RuntimeException('The request body is not empty, but no RequestBodyEncoder implementation was found. Did you forget to inject a RequestBodyEncoder?');
+ if ($this->throwOnErrorStatus && $response->statusCode() >= 400) {
+ throw ResponseException::create($request, $response);
}
- // encode request body
- if ($requestBody && $this->requestBodyEncoder) {
- $encodedRequestBody = $this->requestBodyEncoder->encode($requestBody);
- $stream = $this->streamFactory->createStream($encodedRequestBody);
- $psr7Request = $psr7Request->withBody($stream);
+ return $response;
+ }
+
+ private function createPsr7Request(RequestInterface $request): Psr7RequestInterface
+ {
+ $uri = rtrim($this->baseUri, '/').'/'.ltrim($request->uri(), '/');
+ $psr7Request = $this->requestFactory->createRequest($request->method(), $uri);
+
+ $body = $request->body();
+
+ if (\is_array($body)) {
+ $encoder = $this->resolveEncoder($request);
+ $psr7Request = $psr7Request
+ ->withHeader('Content-Type', $encoder->contentType())
+ ->withBody($this->streamFactory->createStream($encoder->encode($body)));
+ } elseif (\is_string($body)) {
+ $psr7Request = $psr7Request->withBody($this->streamFactory->createStream($body));
}
- // override "global" request headers by request specific headers
+ // request specific headers win over everything set above, Content-Type included
if ($request instanceof HeadersAwareRequestInterface) {
foreach ($request->headers() as $header) {
$psr7Request = $psr7Request->withHeader($header->name(), $header->value());
}
}
- // send psr7 request
- $psr7Response = $this->httpClient->sendRequest($psr7Request);
-
- $body = $psr7Response->getBody()->getContents();
-
- // decode response body
- if (!empty($body) && null !== $this->responseBodyDecoder) {
- $body = $this->responseBodyDecoder->decode($body);
- }
-
- $statusCode = $psr7Response->getStatusCode();
- $headers = $psr7Response->getHeaders();
+ return $psr7Request;
+ }
- $response = new Response($body, $statusCode, $headers);
+ private function resolveEncoder(RequestInterface $request): RequestBodyEncoderInterface
+ {
+ $encoder = $request instanceof BodyEncoderAwareRequestInterface ? $request->bodyEncoder() : null;
+ $encoder ??= $this->requestBodyEncoder;
- // execute response handler
- if ($this->responseHandler) {
- $response = $this->responseHandler->handle($response);
+ if (!$encoder instanceof RequestBodyEncoderInterface) {
+ throw new \LogicException('The request body is an array, but no RequestBodyEncoder was found. Inject one into the Client or set one on the request.');
}
- return $response;
+ return $encoder;
}
}
diff --git a/src/Api/ClientInterface.php b/src/Api/ClientInterface.php
index 7b12cc2..d47805c 100644
--- a/src/Api/ClientInterface.php
+++ b/src/Api/ClientInterface.php
@@ -4,14 +4,18 @@
namespace Api;
+use Api\Exception\ApiExceptionInterface;
use Api\Exception\ResponseException;
+use Api\Exception\TransportException;
use Api\Request\RequestInterface;
use Api\Response\ResponseInterface;
interface ClientInterface
{
/**
- * @throws ResponseException
+ * @throws ResponseException on a 4xx/5xx response (unless the client is told not to)
+ * @throws TransportException when no complete response was received
+ * @throws ApiExceptionInterface
*/
public function request(RequestInterface $request): ResponseInterface;
}
diff --git a/src/Api/ClientTest.php b/src/Api/ClientTest.php
new file mode 100644
index 0000000..1f79aef
--- /dev/null
+++ b/src/Api/ClientTest.php
@@ -0,0 +1,229 @@
+, body: mixed}|null */
+ private ?array $sent = null;
+
+ public function test_it_joins_base_uri_and_request_uri(): void
+ {
+ $this->client(new MockResponse('{}'))->request(new Request(Method::GET, '/items?page=2'));
+
+ self::assertSame('GET', $this->sent['method'] ?? null);
+ self::assertSame('https://api.example.com/rest/v1/items?page=2', $this->sent['url'] ?? null);
+ }
+
+ public function test_it_encodes_an_array_body_and_sets_the_encoders_content_type(): void
+ {
+ $this->client(new MockResponse('{}'))->request(new Request(Method::POST, 'items', ['name' => 'Ball/Racket']));
+
+ self::assertSame('{"name":"Ball/Racket"}', $this->sent['body'] ?? null);
+ self::assertSame(['Content-Type: application/json'], $this->sent['headers']['content-type'] ?? null);
+ }
+
+ public function test_a_request_can_bring_its_own_encoder(): void
+ {
+ $request = new Request(Method::POST, 'token', ['grant_type' => 'client_credentials', 'scope' => 'a b'], bodyEncoder: new FormRequestBodyEncoder());
+
+ $this->client(new MockResponse('{}'))->request($request);
+
+ self::assertSame('grant_type=client_credentials&scope=a+b', $this->sent['body'] ?? null);
+ self::assertSame(['Content-Type: application/x-www-form-urlencoded'], $this->sent['headers']['content-type'] ?? null);
+ }
+
+ public function test_a_string_body_is_sent_as_it_is(): void
+ {
+ $request = (new Request(Method::PUT, 'files/1', "%PDF-1.7\x00\x01"))->addHeader('Content-Type', 'application/pdf');
+
+ $this->client(new MockResponse('', ['http_code' => 204]))->request($request);
+
+ self::assertSame("%PDF-1.7\x00\x01", $this->sent['body'] ?? null);
+ // Header normalizes names to lower case
+ self::assertSame(['content-type: application/pdf'], $this->sent['headers']['content-type'] ?? null);
+ }
+
+ public function test_request_headers_override_handler_and_encoder_headers(): void
+ {
+ $request = (new Request(Method::POST, 'items', ['a' => 1]))->addHeader('Content-Type', 'application/vnd.api+json');
+
+ $this->client(new MockResponse('{}'), new AddHeaderHandler('Accept', 'application/json'))->request($request);
+
+ self::assertSame(['content-type: application/vnd.api+json'], $this->sent['headers']['content-type'] ?? null);
+ self::assertSame(['accept: application/json'], $this->sent['headers']['accept'] ?? null);
+ }
+
+ public function test_an_array_body_without_encoder_is_rejected(): void
+ {
+ $client = new Client(...$this->psr18(new MockResponse('{}')), baseUri: 'https://api.example.com');
+
+ $this->expectException(\LogicException::class);
+
+ $client->request(new Request(Method::POST, 'items', ['a' => 1]));
+ }
+
+ public function test_it_returns_a_lazily_decoded_response(): void
+ {
+ $response = $this->client(new MockResponse('{"id":7}', ['response_headers' => ['X-Request-Id' => 'abc']]))
+ ->request(new Request(Method::GET, 'items/7'));
+
+ self::assertSame(200, $response->statusCode());
+ self::assertSame(['id' => 7], $response->body());
+ self::assertSame('{"id":7}', $response->rawBody());
+ self::assertSame('abc', $response->header('x-request-id'));
+ }
+
+ public function test_a_binary_body_is_only_decoded_when_asked_for(): void
+ {
+ $response = $this->client(new MockResponse("%PDF-1.7\x00"))->request(new Request(Method::GET, 'files/1'));
+
+ self::assertSame("%PDF-1.7\x00", $response->rawBody());
+
+ $this->expectException(DecodingException::class);
+ $response->body();
+ }
+
+ public function test_a_4xx_response_throws_a_client_exception_without_the_body(): void
+ {
+ $client = $this->client(new MockResponse('{"email":"jane@example.com"}', ['http_code' => 422]));
+
+ try {
+ $client->request(new Request(Method::POST, 'members?api_key=secret', ['email' => 'jane@example.com']));
+ self::fail('No exception thrown.');
+ } catch (ClientException $exception) {
+ self::assertSame(422, $exception->getCode());
+ self::assertSame('HTTP 422 returned for "POST members".', $exception->getMessage());
+ self::assertSame(['email' => 'jane@example.com'], $exception->response()->body());
+ }
+ }
+
+ public function test_a_5xx_response_throws_a_server_exception(): void
+ {
+ $this->expectException(ServerException::class);
+ $this->expectExceptionCode(503);
+
+ $this->client(new MockResponse('busy', ['http_code' => 503]))->request(new Request(Method::GET, 'items'));
+ }
+
+ public function test_error_statuses_can_be_returned_instead_of_thrown(): void
+ {
+ $client = new Client(
+ ...$this->psr18(new MockResponse('', ['http_code' => 404])),
+ baseUri: 'https://api.example.com',
+ throwOnErrorStatus: false,
+ );
+
+ self::assertSame(404, $client->request(new Request(Method::GET, 'items/1'))->statusCode());
+ }
+
+ public function test_response_handlers_run_before_the_status_check(): void
+ {
+ $notFound = new class implements ResponseHandlerInterface {
+ public function handle(ResponseInterface $response, RequestInterface $request): ResponseInterface
+ {
+ if (404 === $response->statusCode()) {
+ throw new \DomainException('Member not found');
+ }
+
+ return $response;
+ }
+ };
+
+ $client = new Client(...$this->psr18(new MockResponse('', ['http_code' => 404])), baseUri: 'https://api.example.com', responseHandler: $notFound);
+
+ $this->expectException(\DomainException::class);
+
+ $client->request(new Request(Method::GET, 'members/1'));
+ }
+
+ public function test_a_network_failure_throws_a_transport_exception_with_the_cause_chained(): void
+ {
+ try {
+ $this->client(new MockResponse('', ['error' => 'Idle timeout reached for "https://api.example.com/items?token=secret".']))
+ ->request(new Request(Method::GET, 'items?token=secret'));
+ self::fail('No exception thrown.');
+ } catch (TransportException $exception) {
+ self::assertSame('Request "GET items" failed before a complete response was received.', $exception->getMessage());
+ self::assertStringNotContainsString('secret', $exception->getMessage());
+ self::assertInstanceOf(NetworkExceptionInterface::class, $exception->getPrevious());
+ self::assertTrue($exception->isNetworkError());
+ }
+ }
+
+ private function client(MockResponse $response, ?RequestHandlerInterface $requestHandler = null): Client
+ {
+ return new Client(
+ ...$this->psr18($response),
+ baseUri: 'https://api.example.com/rest/v1/',
+ requestHandler: $requestHandler,
+ requestBodyEncoder: new JsonRequestBodyEncoder(),
+ responseBodyDecoder: new JsonResponseBodyDecoder(),
+ );
+ }
+
+ /**
+ * @return array{httpClient: Psr18Client, requestFactory: Psr18Client, streamFactory: Psr18Client}
+ */
+ private function psr18(MockResponse $response): array
+ {
+ $mock = new MockHttpClient(function (string $method, string $url, array $options) use ($response): MockResponse {
+ $headers = $options['normalized_headers'] ?? [];
+
+ $this->sent = [
+ 'method' => $method,
+ 'url' => $url,
+ 'headers' => \is_array($headers) ? $headers : [],
+ 'body' => $options['body'] ?? null,
+ ];
+
+ return $response;
+ });
+
+ $psr18 = new Psr18Client($mock);
+
+ return ['httpClient' => $psr18, 'requestFactory' => $psr18, 'streamFactory' => $psr18];
+ }
+}
diff --git a/src/Api/ClientsTest.php b/src/Api/ClientsTest.php
index 320abfb..9471745 100644
--- a/src/Api/ClientsTest.php
+++ b/src/Api/ClientsTest.php
@@ -7,31 +7,35 @@
use Api\Request\Encoder\JsonRequestBodyEncoder;
use Api\Request\Handler\AddHeaderHandler;
use Api\Request\Handler\ChainRequestHandler;
+use Api\Request\Header;
use Api\Request\Method;
use Api\Request\Request;
use Api\Response\Decoder\JsonResponseBodyDecoder;
use GuzzleHttp\Psr7\HttpFactory;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\DataProvider;
+use PHPUnit\Framework\Attributes\Group;
+use PHPUnit\Framework\Attributes\UsesClass;
use PHPUnit\Framework\TestCase;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Symfony\Component\HttpClient\Psr18Client;
-/**
- * @covers \Api\Client
- *
- * @uses \Api\Request\Request
- * @uses \Api\Request\Handler\ChainRequestHandler
- * @uses \Api\Request\Handler\AddHeaderHandler
- * @uses \Api\Request\Encoder\JsonRequestBodyEncoder
- * @uses \Api\Response\Decoder\JsonResponseBodyDecoder
- * @uses \Api\Response\Response
- * @uses \Api\Request\Header
- *
- * @group e2e
- */
+#[CoversClass(Client::class)]
+#[UsesClass(Request::class)]
+#[UsesClass(ChainRequestHandler::class)]
+#[UsesClass(AddHeaderHandler::class)]
+#[UsesClass(JsonRequestBodyEncoder::class)]
+#[UsesClass(JsonResponseBodyDecoder::class)]
+#[UsesClass(Response\Response::class)]
+#[UsesClass(Header::class)]
+#[Group('e2e')]
final class ClientsTest extends TestCase
{
+ /**
+ * @return \Generator
+ */
public static function httpClientProvider(): \Generator
{
$symfonyClient = new Psr18Client();
@@ -41,9 +45,7 @@ public static function httpClientProvider(): \Generator
yield 'Guzzle Client' => [new \GuzzleHttp\Client(), $guzzleHttpFactory, $guzzleHttpFactory];
}
- /**
- * @dataProvider httpClientProvider
- */
+ #[DataProvider('httpClientProvider')]
public function test_it_works_using_different_http_clients(
ClientInterface $httpClient,
RequestFactoryInterface $requestFactory,
@@ -57,7 +59,6 @@ public function test_it_works_using_different_http_clients(
new ChainRequestHandler([
new AddHeaderHandler('Authorization', 'Bearer api_key'),
new AddHeaderHandler('Accept', 'application/json'),
- new AddHeaderHandler('Content-Type', 'application/json'),
]),
null,
new JsonRequestBodyEncoder(),
@@ -70,11 +71,13 @@ public function test_it_works_using_different_http_clients(
self::assertSame(200, $response->statusCode());
$body = $response->body();
- self::assertStringContainsString($request->uri(), $body['url']); /* @phpstan-ignore-line */
- self::assertSame($request->method(), $body['method']); /* @phpstan-ignore-line */
- self::assertSame('Bearer api_key', $body['headers']['Authorization']); /* @phpstan-ignore-line */
- self::assertSame('application/json', $body['headers']['Accept']); /* @phpstan-ignore-line */
- self::assertSame('application/json', $body['headers']['Content-Type']); /* @phpstan-ignore-line */
+ self::assertIsArray($body);
+ self::assertIsString($body['url'] ?? null);
+ self::assertIsArray($body['headers'] ?? null);
+ self::assertStringContainsString($request->uri(), $body['url']);
+ self::assertSame($request->method(), $body['method'] ?? null);
+ self::assertSame('Bearer api_key', $body['headers']['Authorization'] ?? null);
+ self::assertSame('application/json', $body['headers']['Accept'] ?? null);
}
}
diff --git a/src/Api/Clock/ClockInterface.php b/src/Api/Clock/ClockInterface.php
new file mode 100644
index 0000000..698efd0
--- /dev/null
+++ b/src/Api/Clock/ClockInterface.php
@@ -0,0 +1,13 @@
+ */
+ private array $sleeps = [];
+
+ public function __construct(\DateTimeImmutable|string $now = 'now')
+ {
+ $this->now = \is_string($now) ? new \DateTimeImmutable($now) : $now;
+ }
+
+ public function now(): \DateTimeImmutable
+ {
+ return $this->now;
+ }
+
+ public function sleep(float $seconds): void
+ {
+ $this->sleeps[] = $seconds;
+ $this->now = $this->now->modify(sprintf('%+d microseconds', (int) round($seconds * 1_000_000)));
+ }
+
+ /**
+ * @return list
+ */
+ public function sleeps(): array
+ {
+ return $this->sleeps;
+ }
+}
diff --git a/src/Api/Clock/MockClockTest.php b/src/Api/Clock/MockClockTest.php
new file mode 100644
index 0000000..fb12706
--- /dev/null
+++ b/src/Api/Clock/MockClockTest.php
@@ -0,0 +1,39 @@
+sleep(1.5);
+ $clock->sleep(0.25);
+
+ self::assertSame('2026-10-25 12:00:01.750000', $clock->now()->format('Y-m-d H:i:s.u'));
+ self::assertSame([1.5, 0.25], $clock->sleeps());
+ }
+
+ public function test_native_clock(): void
+ {
+ $clock = new NativeClock();
+ $before = $clock->now();
+
+ $clock->sleep(0.01);
+ $clock->sleep(0.0);
+
+ // both ends from the same clock, so microsecond truncation cannot make this flaky
+ $elapsedMicroseconds = (int) $clock->now()->format('Uu') - (int) $before->format('Uu');
+ self::assertGreaterThanOrEqual(10_000, $elapsedMicroseconds);
+ }
+}
diff --git a/src/Api/Clock/NativeClock.php b/src/Api/Clock/NativeClock.php
new file mode 100644
index 0000000..454b8f3
--- /dev/null
+++ b/src/Api/Clock/NativeClock.php
@@ -0,0 +1,20 @@
+ 0) {
+ usleep((int) round($seconds * 1_000_000));
+ }
+ }
+}
diff --git a/src/Api/Exception/ApiExceptionInterface.php b/src/Api/Exception/ApiExceptionInterface.php
new file mode 100644
index 0000000..462fdec
--- /dev/null
+++ b/src/Api/Exception/ApiExceptionInterface.php
@@ -0,0 +1,12 @@
+statusCode();
+
+ if (400 > $code || $code >= 500) {
+ throw new \InvalidArgumentException(sprintf('Class "%s" requires a response with a 4xx status code, "%d" given.', self::class, $code));
}
- parent::__construct($code, $message);
+
+ parent::__construct($request, $response, $previous);
}
}
diff --git a/src/Api/Exception/ClientExceptionTest.php b/src/Api/Exception/ClientExceptionTest.php
index ee68f28..4f1392b 100644
--- a/src/Api/Exception/ClientExceptionTest.php
+++ b/src/Api/Exception/ClientExceptionTest.php
@@ -4,34 +4,44 @@
namespace Api\Exception;
+use Api\Request\Method;
+use Api\Request\Request;
+use Api\Response\Response;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\DataProvider;
+use PHPUnit\Framework\Attributes\Group;
+use PHPUnit\Framework\Attributes\UsesClass;
use PHPUnit\Framework\TestCase;
-/**
- * @covers \Api\Exception\ClientException
- * @covers \Api\Exception\ResponseException
- *
- * @group unit
- */
+#[CoversClass(ClientException::class)]
+#[UsesClass(ResponseException::class)]
+#[UsesClass(RequestDescription::class)]
+#[UsesClass(Request::class)]
+#[UsesClass(Response::class)]
+#[Group('unit')]
final class ClientExceptionTest extends TestCase
{
public function test_it_can_be_created(): void
{
- $exception = new ClientException(400, 'Bad Request');
- self::assertSame('400 Bad Request', $exception->getMessage());
+ $exception = new ClientException(new Request(Method::GET, 'items'), new Response('', 400));
+
+ self::assertSame('HTTP 400 returned for "GET items".', $exception->getMessage());
+ self::assertSame(400, $exception->getCode());
}
- /**
- * @dataProvider provideInvalidCodes
- */
+ #[DataProvider('provideInvalidCodes')]
public function test_it_throws_InvalidArgumentException_on_non_4xx_code(int $invalidCode): void
{
$this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('Class "Api\Exception\ClientException" constructor argument $code must be a 4xx status code');
+ $this->expectExceptionMessage('Class "Api\Exception\ClientException" requires a response with a 4xx status code');
- new ClientException($invalidCode, 'invalid code');
+ new ClientException(new Request(Method::GET, 'items'), new Response('', $invalidCode));
}
- public function provideInvalidCodes(): iterable
+ /**
+ * @return iterable
+ */
+ public static function provideInvalidCodes(): iterable
{
yield [500];
yield [300];
diff --git a/src/Api/Exception/DecodingException.php b/src/Api/Exception/DecodingException.php
new file mode 100644
index 0000000..7e38315
--- /dev/null
+++ b/src/Api/Exception/DecodingException.php
@@ -0,0 +1,16 @@
+uri(), 2)[0];
+
+ return sprintf('%s %s', strtoupper($request->method()), '' === $path ? '/' : $path);
+ }
+}
diff --git a/src/Api/Exception/ResponseException.php b/src/Api/Exception/ResponseException.php
index 95c8285..a7e59bd 100644
--- a/src/Api/Exception/ResponseException.php
+++ b/src/Api/Exception/ResponseException.php
@@ -4,10 +4,55 @@
namespace Api\Exception;
-class ResponseException extends \RuntimeException
+use Api\Request\RequestInterface;
+use Api\Response\ResponseInterface;
+
+/**
+ * Thrown when the API answered with an error status code.
+ *
+ * The exception code is the HTTP status code. The message never contains the response body,
+ * because bodies of error responses often echo back submitted (personal) data; use response()
+ * when the body is really needed.
+ *
+ * @see ResponseExceptionTest
+ */
+class ResponseException extends \RuntimeException implements ApiExceptionInterface
{
- public function __construct(int $code, string $message)
+ public function __construct(
+ private readonly RequestInterface $request,
+ private readonly ResponseInterface $response,
+ ?\Throwable $previous = null,
+ ) {
+ parent::__construct(
+ sprintf('HTTP %d returned for "%s".', $response->statusCode(), RequestDescription::of($request)),
+ $response->statusCode(),
+ $previous,
+ );
+ }
+
+ public static function create(RequestInterface $request, ResponseInterface $response): self
+ {
+ $statusCode = $response->statusCode();
+
+ return match (true) {
+ $statusCode >= 500 => new ServerException($request, $response),
+ $statusCode >= 400 => new ClientException($request, $response),
+ default => new self($request, $response),
+ };
+ }
+
+ public function request(): RequestInterface
+ {
+ return $this->request;
+ }
+
+ public function response(): ResponseInterface
+ {
+ return $this->response;
+ }
+
+ public function statusCode(): int
{
- parent::__construct(sprintf('%d %s', $code, $message));
+ return $this->response->statusCode();
}
}
diff --git a/src/Api/Exception/ResponseExceptionTest.php b/src/Api/Exception/ResponseExceptionTest.php
new file mode 100644
index 0000000..0afbdf4
--- /dev/null
+++ b/src/Api/Exception/ResponseExceptionTest.php
@@ -0,0 +1,56 @@
+ 'Jane']);
+ $response = new Response('{"name":"Jane"}', 409);
+
+ $exception = ResponseException::create($request, $response);
+
+ self::assertSame('HTTP 409 returned for "POST /members".', $exception->getMessage());
+ self::assertSame(409, $exception->getCode());
+ self::assertSame(409, $exception->statusCode());
+ self::assertSame($request, $exception->request());
+ self::assertSame($response, $exception->response());
+ }
+
+ public function test_the_cause_can_be_chained(): void
+ {
+ $cause = new \RuntimeException('cause');
+
+ $exception = new ResponseException(new Request(Method::GET, ''), new Response('', 302), $cause);
+
+ self::assertSame($cause, $exception->getPrevious());
+ self::assertSame('HTTP 302 returned for "GET /".', $exception->getMessage());
+ }
+}
diff --git a/src/Api/Exception/ServerException.php b/src/Api/Exception/ServerException.php
index de51534..251e5ab 100644
--- a/src/Api/Exception/ServerException.php
+++ b/src/Api/Exception/ServerException.php
@@ -4,16 +4,22 @@
namespace Api\Exception;
+use Api\Request\RequestInterface;
+use Api\Response\ResponseInterface;
+
/**
* @see ServerExceptionTest
*/
final class ServerException extends ResponseException
{
- public function __construct(int $code, string $message)
+ public function __construct(RequestInterface $request, ResponseInterface $response, ?\Throwable $previous = null)
{
- if ($code < 500) {
- throw new \InvalidArgumentException(sprintf('Class "%s" constructor argument $code must be a 5xx status code, "%d" given.', self::class, $code));
+ $code = $response->statusCode();
+
+ if (500 > $code || $code >= 600) {
+ throw new \InvalidArgumentException(sprintf('Class "%s" requires a response with a 5xx status code, "%d" given.', self::class, $code));
}
- parent::__construct($code, $message);
+
+ parent::__construct($request, $response, $previous);
}
}
diff --git a/src/Api/Exception/ServerExceptionTest.php b/src/Api/Exception/ServerExceptionTest.php
index 078f834..feb10e2 100644
--- a/src/Api/Exception/ServerExceptionTest.php
+++ b/src/Api/Exception/ServerExceptionTest.php
@@ -4,36 +4,47 @@
namespace Api\Exception;
+use Api\Request\Method;
+use Api\Request\Request;
+use Api\Response\Response;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\DataProvider;
+use PHPUnit\Framework\Attributes\Group;
+use PHPUnit\Framework\Attributes\UsesClass;
use PHPUnit\Framework\TestCase;
-/**
- * @covers \Api\Exception\ServerException
- * @covers \Api\Exception\ResponseException
- *
- * @group unit
- */
+#[CoversClass(ServerException::class)]
+#[UsesClass(ResponseException::class)]
+#[UsesClass(RequestDescription::class)]
+#[UsesClass(Request::class)]
+#[UsesClass(Response::class)]
+#[Group('unit')]
final class ServerExceptionTest extends TestCase
{
public function test_it_can_be_created(): void
{
- $exception = new ServerException(500, 'Server Error');
- self::assertSame('500 Server Error', $exception->getMessage());
+ $exception = new ServerException(new Request(Method::GET, 'items'), new Response('', 500));
+
+ self::assertSame('HTTP 500 returned for "GET items".', $exception->getMessage());
+ self::assertSame(500, $exception->getCode());
}
- /**
- * @dataProvider provideInvalidCodes
- */
- public function test_it_throws_InvalidArgumentException_on_non_4xx_code(int $invalidCode): void
+ #[DataProvider('provideInvalidCodes')]
+ public function test_it_throws_InvalidArgumentException_on_non_5xx_code(int $invalidCode): void
{
$this->expectException(\InvalidArgumentException::class);
- $this->expectExceptionMessage('Class "Api\Exception\ServerException" constructor argument $code must be a 5xx status code');
+ $this->expectExceptionMessage('Class "Api\Exception\ServerException" requires a response with a 5xx status code');
- new ServerException($invalidCode, 'invalid code');
+ new ServerException(new Request(Method::GET, 'items'), new Response('', $invalidCode));
}
- public function provideInvalidCodes(): iterable
+ /**
+ * @return iterable
+ */
+ public static function provideInvalidCodes(): iterable
{
yield [400];
+ yield [600];
yield [300];
yield [200];
yield [100];
diff --git a/src/Api/Exception/TransportException.php b/src/Api/Exception/TransportException.php
new file mode 100644
index 0000000..d0c97d9
--- /dev/null
+++ b/src/Api/Exception/TransportException.php
@@ -0,0 +1,45 @@
+request;
+ }
+
+ /**
+ * False when the PSR-18 client rejected the request itself (malformed request):
+ * sending it again cannot succeed.
+ */
+ public function isNetworkError(): bool
+ {
+ return !$this->getPrevious() instanceof RequestExceptionInterface;
+ }
+}
diff --git a/src/Api/Exception/TransportExceptionTest.php b/src/Api/Exception/TransportExceptionTest.php
new file mode 100644
index 0000000..8587250
--- /dev/null
+++ b/src/Api/Exception/TransportExceptionTest.php
@@ -0,0 +1,47 @@
+getMessage());
+ self::assertSame(0, $exception->getCode());
+ self::assertSame($cause, $exception->getPrevious());
+ self::assertSame($request, $exception->request());
+ self::assertTrue($exception->isNetworkError());
+ }
+
+ public function test_a_rejected_request_is_no_network_error(): void
+ {
+ $cause = new class extends \InvalidArgumentException implements RequestExceptionInterface {
+ public function getRequest(): Psr7RequestInterface
+ {
+ throw new \LogicException('not needed');
+ }
+ };
+
+ self::assertFalse((new TransportException(new Request(Method::GET, 'x'), $cause))->isNetworkError());
+ }
+}
diff --git a/src/Api/Request/BodyEncoderAwareRequestInterface.php b/src/Api/Request/BodyEncoderAwareRequestInterface.php
new file mode 100644
index 0000000..4ba8695
--- /dev/null
+++ b/src/Api/Request/BodyEncoderAwareRequestInterface.php
@@ -0,0 +1,14 @@
+encode(['url' => 'https://x.test/ä']));
+ self::assertSame('application/json', $encoder->contentType());
+ }
+
+ public function test_json_throws_on_invalid_input(): void
+ {
+ $this->expectException(\JsonException::class);
+
+ (new JsonRequestBodyEncoder())->encode(['invalid' => "\xB1"]);
+ }
+
+ public function test_form(): void
+ {
+ $encoder = new FormRequestBodyEncoder();
+
+ self::assertSame('grant_type=client_credentials&scope=read+write&ids%5B0%5D=1', $encoder->encode(['grant_type' => 'client_credentials', 'scope' => 'read write', 'ids' => [1]]));
+ self::assertSame('application/x-www-form-urlencoded', $encoder->contentType());
+ }
+}
diff --git a/src/Api/Request/Encoder/FormRequestBodyEncoder.php b/src/Api/Request/Encoder/FormRequestBodyEncoder.php
new file mode 100644
index 0000000..e1c1889
--- /dev/null
+++ b/src/Api/Request/Encoder/FormRequestBodyEncoder.php
@@ -0,0 +1,23 @@
+flags | \JSON_THROW_ON_ERROR);
+ }
+
+ public function contentType(): string
+ {
+ return 'application/json';
}
}
diff --git a/src/Api/Request/IsDelete.php b/src/Api/Request/IsDelete.php
index 3e8ebd1..ec821f2 100644
--- a/src/Api/Request/IsDelete.php
+++ b/src/Api/Request/IsDelete.php
@@ -11,7 +11,7 @@ public function method(): string
return Method::DELETE->value;
}
- public function body(): ?array
+ public function body(): null
{
return null;
}
diff --git a/src/Api/Request/IsGet.php b/src/Api/Request/IsGet.php
index e9b5cd2..5c83e4a 100644
--- a/src/Api/Request/IsGet.php
+++ b/src/Api/Request/IsGet.php
@@ -11,7 +11,7 @@ public function method(): string
return Method::GET->value;
}
- public function body(): ?array
+ public function body(): null
{
return null;
}
diff --git a/src/Api/Request/Method.php b/src/Api/Request/Method.php
index 84c02f1..8cf99c6 100644
--- a/src/Api/Request/Method.php
+++ b/src/Api/Request/Method.php
@@ -7,8 +7,21 @@
enum Method: string
{
case GET = 'GET';
+ case HEAD = 'HEAD';
+ case OPTIONS = 'OPTIONS';
case POST = 'POST';
case PUT = 'PUT';
case PATCH = 'PATCH';
case DELETE = 'DELETE';
+
+ /**
+ * Idempotent per RFC 9110: sending the request twice has the same effect as sending it once.
+ */
+ public function isIdempotent(): bool
+ {
+ return match ($this) {
+ self::POST, self::PATCH => false,
+ default => true,
+ };
+ }
}
diff --git a/src/Api/Request/Request.php b/src/Api/Request/Request.php
index 990f0a0..fa72ec9 100644
--- a/src/Api/Request/Request.php
+++ b/src/Api/Request/Request.php
@@ -4,29 +4,41 @@
namespace Api\Request;
-class Request implements HeadersAwareRequestInterface
+class Request implements HeadersAwareRequestInterface, BodyEncoderAwareRequestInterface
{
use HeadersAwareRequestTrait;
/**
- * @param Header[] $headers
+ * @param array|string|null $body
+ * @param Header[] $headers
*/
public function __construct(
public readonly Method $method,
public readonly string $uri,
- private ?array $body = null,
+ private array|string|null $body = null,
array $headers = [],
+ private ?RequestBodyEncoderInterface $bodyEncoder = null,
) {
$this->headers = $headers;
}
- public function setBody(array $body): self
+ /**
+ * @param array|string $body
+ */
+ public function setBody(array|string $body): self
{
$this->body = $body;
return $this;
}
+ public function setBodyEncoder(RequestBodyEncoderInterface $bodyEncoder): self
+ {
+ $this->bodyEncoder = $bodyEncoder;
+
+ return $this;
+ }
+
public function method(): string
{
return $this->method->value;
@@ -37,8 +49,13 @@ public function uri(): string
return $this->uri;
}
- public function body(): ?array
+ public function body(): array|string|null
{
return $this->body;
}
+
+ public function bodyEncoder(): ?RequestBodyEncoderInterface
+ {
+ return $this->bodyEncoder;
+ }
}
diff --git a/src/Api/Request/RequestBodyEncoderInterface.php b/src/Api/Request/RequestBodyEncoderInterface.php
index ce2dbe9..bb209f7 100644
--- a/src/Api/Request/RequestBodyEncoderInterface.php
+++ b/src/Api/Request/RequestBodyEncoderInterface.php
@@ -6,5 +6,13 @@
interface RequestBodyEncoderInterface
{
+ /**
+ * @param array $requestBody
+ */
public function encode(array $requestBody): string;
+
+ /**
+ * Sent as Content-Type unless the request sets that header itself.
+ */
+ public function contentType(): string;
}
diff --git a/src/Api/Request/RequestInterface.php b/src/Api/Request/RequestInterface.php
index 00c392a..86e8da9 100644
--- a/src/Api/Request/RequestInterface.php
+++ b/src/Api/Request/RequestInterface.php
@@ -10,5 +10,10 @@ public function method(): string;
public function uri(): string;
- public function body(): ?array;
+ /**
+ * An array is encoded by a RequestBodyEncoderInterface, a string is sent as it is.
+ *
+ * @return array|string|null
+ */
+ public function body(): array|string|null;
}
diff --git a/src/Api/Request/TraitsTest.php b/src/Api/Request/TraitsTest.php
index 0120d1b..56c72f8 100644
--- a/src/Api/Request/TraitsTest.php
+++ b/src/Api/Request/TraitsTest.php
@@ -4,21 +4,23 @@
namespace Api\Request;
+use PHPUnit\Framework\Attributes\CoversTrait;
+use PHPUnit\Framework\Attributes\Group;
+use PHPUnit\Framework\Attributes\UsesClass;
use PHPUnit\Framework\TestCase;
-/**
- * @covers \Api\Request\IsGet
- * @covers \Api\Request\IsPost
- * @covers \Api\Request\IsPut
- * @covers \Api\Request\IsPatch
- * @covers \Api\Request\IsDelete
- */
+#[CoversTrait(IsGet::class)]
+#[CoversTrait(IsPost::class)]
+#[CoversTrait(IsPut::class)]
+#[CoversTrait(IsPatch::class)]
+#[CoversTrait(IsDelete::class)]
+#[UsesClass(Method::class)]
+#[Group('unit')]
final class TraitsTest extends TestCase
{
public function test_traits(): void
{
self::assertSame(Method::GET->value, (new GetRequest())->method());
- self::assertSame(null, (new GetRequest())->body());
self::assertSame(Method::POST->value, (new PostRequest())->method());
@@ -27,7 +29,6 @@ public function test_traits(): void
self::assertSame(Method::PATCH->value, (new PatchRequest())->method());
self::assertSame(Method::DELETE->value, (new DeleteRequest())->method());
- self::assertSame(null, (new DeleteRequest())->body());
}
}
diff --git a/src/Api/Response/Decoder/JsonResponseBodyDecoder.php b/src/Api/Response/Decoder/JsonResponseBodyDecoder.php
index 10df3f7..1c4b6e1 100644
--- a/src/Api/Response/Decoder/JsonResponseBodyDecoder.php
+++ b/src/Api/Response/Decoder/JsonResponseBodyDecoder.php
@@ -9,11 +9,10 @@
final class JsonResponseBodyDecoder implements ResponseBodyDecoderInterface
{
/**
- * @return mixed[]
+ * @throws \JsonException
*/
- public function decode(string $responseBody): array
+ public function decode(string $responseBody): mixed
{
- // todo: handle json errors and types
- return (array) json_decode($responseBody, associative: true, flags: JSON_THROW_ON_ERROR);
+ return json_decode($responseBody, associative: true, flags: \JSON_THROW_ON_ERROR);
}
}
diff --git a/src/Api/Response/Handler/ChainResponseHandler.php b/src/Api/Response/Handler/ChainResponseHandler.php
index b20fa35..e142b78 100644
--- a/src/Api/Response/Handler/ChainResponseHandler.php
+++ b/src/Api/Response/Handler/ChainResponseHandler.php
@@ -4,25 +4,26 @@
namespace Api\Response\Handler;
-use Api\Response\Response;
+use Api\Request\RequestInterface;
use Api\Response\ResponseHandlerInterface;
+use Api\Response\ResponseInterface;
use Webmozart\Assert\Assert;
final readonly class ChainResponseHandler implements ResponseHandlerInterface
{
/**
- * @param ResponseHandlerInterface[] $responseHandlers
+ * @param iterable $responseHandlers
*/
public function __construct(
- private iterable $responseHandlers
+ private iterable $responseHandlers,
) {
Assert::allIsInstanceOf($responseHandlers, ResponseHandlerInterface::class);
}
- public function handle(Response $response): Response
+ public function handle(ResponseInterface $response, RequestInterface $request): ResponseInterface
{
foreach ($this->responseHandlers as $responseHandler) {
- $response = $responseHandler->handle($response);
+ $response = $responseHandler->handle($response, $request);
}
return $response;
diff --git a/src/Api/Response/Response.php b/src/Api/Response/Response.php
index ed43b77..47415af 100644
--- a/src/Api/Response/Response.php
+++ b/src/Api/Response/Response.php
@@ -4,30 +4,73 @@
namespace Api\Response;
+use Api\Exception\DecodingException;
+
+/**
+ * @see ResponseTest
+ */
final class Response implements ResponseInterface
{
+ private bool $decoded = false;
+
+ private mixed $body = null;
+
+ /**
+ * @param array> $headers
+ */
public function __construct(
- private readonly mixed $body,
+ private readonly string $rawBody,
private readonly int $statusCode,
- private readonly array $headers = []
+ private readonly array $headers = [],
+ private readonly ?ResponseBodyDecoderInterface $decoder = null,
) {
}
+ /**
+ * Decoded on first access, so a response that is never read (or only read raw) is never decoded.
+ */
public function body(): mixed
{
+ if (!$this->decoder instanceof ResponseBodyDecoderInterface || '' === $this->rawBody) {
+ return $this->rawBody;
+ }
+
+ if (!$this->decoded) {
+ try {
+ $this->body = $this->decoder->decode($this->rawBody);
+ } catch (\Throwable $exception) {
+ throw new DecodingException($this->statusCode, $exception);
+ }
+
+ $this->decoded = true;
+ }
+
return $this->body;
}
+ public function rawBody(): string
+ {
+ return $this->rawBody;
+ }
+
public function statusCode(): int
{
return $this->statusCode;
}
- /**
- * @return mixed[]
- */
public function headers(): array
{
return $this->headers;
}
+
+ public function header(string $name): ?string
+ {
+ foreach ($this->headers as $headerName => $values) {
+ if (0 === strcasecmp($headerName, $name)) {
+ return $values[0] ?? null;
+ }
+ }
+
+ return null;
+ }
}
diff --git a/src/Api/Response/ResponseBodyDecoderInterface.php b/src/Api/Response/ResponseBodyDecoderInterface.php
index bcb713c..a23dac7 100644
--- a/src/Api/Response/ResponseBodyDecoderInterface.php
+++ b/src/Api/Response/ResponseBodyDecoderInterface.php
@@ -6,5 +6,8 @@
interface ResponseBodyDecoderInterface
{
- public function decode(string $responseBody): array;
+ /**
+ * @throws \Throwable when the body cannot be decoded; Response turns it into a DecodingException
+ */
+ public function decode(string $responseBody): mixed;
}
diff --git a/src/Api/Response/ResponseHandlerInterface.php b/src/Api/Response/ResponseHandlerInterface.php
index b3ca67b..a643b93 100644
--- a/src/Api/Response/ResponseHandlerInterface.php
+++ b/src/Api/Response/ResponseHandlerInterface.php
@@ -4,12 +4,13 @@
namespace Api\Response;
-use Api\Exception\ResponseException;
+use Api\Request\RequestInterface;
+/**
+ * Runs before the client checks the status code, so a handler can turn an expected
+ * error response (e.g. 404 = "member not found") into a domain exception of its own.
+ */
interface ResponseHandlerInterface
{
- /**
- * @throws ResponseException
- */
- public function handle(Response $response): Response;
+ public function handle(ResponseInterface $response, RequestInterface $request): ResponseInterface;
}
diff --git a/src/Api/Response/ResponseInterface.php b/src/Api/Response/ResponseInterface.php
index 226dd80..d2a4d55 100644
--- a/src/Api/Response/ResponseInterface.php
+++ b/src/Api/Response/ResponseInterface.php
@@ -4,11 +4,31 @@
namespace Api\Response;
+use Api\Exception\DecodingException;
+
interface ResponseInterface
{
public function statusCode(): int;
+ /**
+ * The decoded body, or the raw body when no decoder is configured or the body is empty.
+ *
+ * @throws DecodingException
+ */
public function body(): mixed;
+ /**
+ * The body exactly as received, e.g. for binary downloads.
+ */
+ public function rawBody(): string;
+
+ /**
+ * @return array>
+ */
public function headers(): array;
+
+ /**
+ * The first value of a header, looked up case-insensitively.
+ */
+ public function header(string $name): ?string;
}
diff --git a/src/Api/Response/ResponseTest.php b/src/Api/Response/ResponseTest.php
new file mode 100644
index 0000000..b4fe86d
--- /dev/null
+++ b/src/Api/Response/ResponseTest.php
@@ -0,0 +1,70 @@
+body());
+ }
+
+ public function test_an_empty_body_is_not_decoded(): void
+ {
+ self::assertSame('', (new Response('', 204, [], new JsonResponseBodyDecoder()))->body());
+ }
+
+ public function test_the_body_is_decoded_once(): void
+ {
+ $decoder = new class implements ResponseBodyDecoderInterface {
+ public int $calls = 0;
+
+ public function decode(string $responseBody): mixed
+ {
+ ++$this->calls;
+
+ return ['decoded' => $responseBody];
+ }
+ };
+
+ $response = new Response('x', 200, [], $decoder);
+
+ self::assertSame(0, $decoder->calls);
+ self::assertSame(['decoded' => 'x'], $response->body());
+ self::assertSame(['decoded' => 'x'], $response->body());
+ self::assertSame(1, $decoder->calls);
+ }
+
+ public function test_a_decoding_failure_is_wrapped_without_the_body(): void
+ {
+ try {
+ (new Response('secret', 502, [], new JsonResponseBodyDecoder()))->body();
+ self::fail('No exception thrown.');
+ } catch (DecodingException $exception) {
+ self::assertSame(502, $exception->getCode());
+ self::assertStringNotContainsString('secret', $exception->getMessage());
+ self::assertInstanceOf(\JsonException::class, $exception->getPrevious());
+ }
+ }
+
+ public function test_headers_are_looked_up_case_insensitively(): void
+ {
+ $response = new Response('', 200, ['Retry-After' => ['5', '6']]);
+
+ self::assertSame('5', $response->header('retry-after'));
+ self::assertNull($response->header('X-Missing'));
+ }
+}
diff --git a/src/Api/Retry/GenericRetryStrategy.php b/src/Api/Retry/GenericRetryStrategy.php
new file mode 100644
index 0000000..02f0e4f
--- /dev/null
+++ b/src/Api/Retry/GenericRetryStrategy.php
@@ -0,0 +1,161 @@
+ GenericRetryStrategy::IDEMPOTENT_METHODS, 429])
+ *
+ * Delays grow exponentially (delay * multiplier^(retry-1)), get +/- jitter and are capped at
+ * maxDelay. A Retry-After header is honoured; when it asks for longer than maxDelay the request
+ * is not retried, since retrying earlier than the server asked would only fail again.
+ *
+ * @see GenericRetryStrategyTest
+ */
+final readonly class GenericRetryStrategy implements RetryStrategyInterface
+{
+ public const IDEMPOTENT_METHODS = ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE'];
+
+ public const DEFAULT_RETRY_STATUS_CODES = [
+ 423 => self::IDEMPOTENT_METHODS,
+ 425 => self::IDEMPOTENT_METHODS,
+ 429,
+ 500 => self::IDEMPOTENT_METHODS,
+ 502 => self::IDEMPOTENT_METHODS,
+ 503 => self::IDEMPOTENT_METHODS,
+ 504 => self::IDEMPOTENT_METHODS,
+ ];
+
+ /** @var array|null> status code => methods, null for every method */
+ private array $statusCodes;
+
+ /**
+ * @param array> $statusCodes
+ * @param float $delay seconds before the first retry
+ * @param float $jitter 0.1 = each delay varies by up to +/- 10%
+ */
+ public function __construct(
+ array $statusCodes = self::DEFAULT_RETRY_STATUS_CODES,
+ private bool $retryNetworkErrors = true,
+ private float $delay = 1.0,
+ private float $multiplier = 2.0,
+ private float $maxDelay = 30.0,
+ private float $jitter = 0.1,
+ private ClockInterface $clock = new NativeClock(),
+ ) {
+ Assert::greaterThanEq($delay, 0.0);
+ Assert::greaterThanEq($multiplier, 1.0);
+ Assert::greaterThanEq($maxDelay, $delay);
+ Assert::range($jitter, 0.0, 1.0);
+
+ $normalized = [];
+ foreach ($statusCodes as $key => $value) {
+ if (\is_int($value)) {
+ $normalized[$value] = null;
+ } else {
+ $normalized[$key] = array_map(strtoupper(...), $value);
+ }
+ }
+ $this->statusCodes = $normalized;
+ }
+
+ public function getDelay(RequestInterface $request, ResponseException|TransportException $failure, int $retryCount): ?float
+ {
+ $method = strtoupper($request->method());
+
+ if ($failure instanceof TransportException) {
+ $retryable = $this->retryNetworkErrors && $failure->isNetworkError() && $this->isIdempotent($method);
+
+ return $retryable ? $this->backoff($retryCount) : null;
+ }
+
+ if (!$this->isRetryableStatus($failure->statusCode(), $method)) {
+ return null;
+ }
+
+ $delay = $this->backoff($retryCount);
+ $retryAfter = $this->retryAfter($failure->response()->header('Retry-After'));
+
+ if (null === $retryAfter) {
+ return $delay;
+ }
+
+ return $retryAfter > $this->maxDelay ? null : max($delay, $retryAfter);
+ }
+
+ private function isRetryableStatus(int $statusCode, string $method): bool
+ {
+ if (!\array_key_exists($statusCode, $this->statusCodes)) {
+ return false;
+ }
+
+ $methods = $this->statusCodes[$statusCode];
+
+ return null === $methods || \in_array($method, $methods, true);
+ }
+
+ private function isIdempotent(string $method): bool
+ {
+ return Method::tryFrom($method)?->isIdempotent() ?? false;
+ }
+
+ private function backoff(int $retryCount): float
+ {
+ $delay = $this->delay * $this->multiplier ** max(0, $retryCount - 1);
+
+ if ($this->jitter > 0) {
+ // uniformly in [-jitter, +jitter]
+ $delay *= 1 + $this->jitter * random_int(-1_000_000, 1_000_000) / 1_000_000;
+ }
+
+ return min($delay, $this->maxDelay);
+ }
+
+ /**
+ * Retry-After is either delay-seconds or an HTTP-date (RFC 9110, section 10.2.3).
+ */
+ private function retryAfter(?string $value): ?float
+ {
+ $value = trim($value ?? '');
+
+ if ('' === $value) {
+ return null;
+ }
+
+ if (ctype_digit($value)) {
+ return (float) $value;
+ }
+
+ // IMF-fixdate, always GMT: "Sun, 06 Nov 1994 08:49:37 GMT"
+ $date = \DateTimeImmutable::createFromFormat('!D, d M Y H:i:s \G\M\T', $value, new \DateTimeZone('UTC'));
+
+ if (false === $date) {
+ return null;
+ }
+
+ $seconds = (float) $date->format('U.u') - (float) $this->clock->now()->format('U.u');
+
+ return max(0.0, $seconds);
+ }
+}
diff --git a/src/Api/Retry/GenericRetryStrategyTest.php b/src/Api/Retry/GenericRetryStrategyTest.php
new file mode 100644
index 0000000..d6d1579
--- /dev/null
+++ b/src/Api/Retry/GenericRetryStrategyTest.php
@@ -0,0 +1,178 @@
+
+ */
+ public static function defaultStatusCodes(): iterable
+ {
+ yield 'GET 503' => [Method::GET, 503, true];
+ yield 'PUT 500' => [Method::PUT, 500, true];
+ yield 'DELETE 423' => [Method::DELETE, 423, true];
+ yield 'POST 503' => [Method::POST, 503, false];
+ yield 'PATCH 502' => [Method::PATCH, 502, false];
+ yield 'POST 429' => [Method::POST, 429, true];
+ yield 'GET 429' => [Method::GET, 429, true];
+ yield 'GET 404' => [Method::GET, 404, false];
+ yield 'GET 501' => [Method::GET, 501, false];
+ }
+
+ #[DataProvider('defaultStatusCodes')]
+ public function test_default_status_codes_respect_idempotency(Method $method, int $statusCode, bool $retried): void
+ {
+ $delay = $this->strategy()->getDelay(...$this->failure($method, $statusCode));
+
+ self::assertSame($retried, null !== $delay);
+ }
+
+ public function test_delays_grow_exponentially_and_are_capped(): void
+ {
+ $strategy = $this->strategy(delay: 1.0, multiplier: 3.0, maxDelay: 5.0);
+ [$request, $failure] = $this->failure(Method::GET, 503);
+
+ self::assertSame(1.0, $strategy->getDelay($request, $failure, 1));
+ self::assertSame(3.0, $strategy->getDelay($request, $failure, 2));
+ self::assertSame(5.0, $strategy->getDelay($request, $failure, 3));
+ }
+
+ public function test_a_flat_delay_is_possible(): void
+ {
+ $strategy = $this->strategy(delay: 20.0, multiplier: 1.0, maxDelay: 20.0);
+ [$request, $failure] = $this->failure(Method::GET, 503);
+
+ self::assertSame(20.0, $strategy->getDelay($request, $failure, 3));
+ }
+
+ public function test_jitter_stays_within_bounds(): void
+ {
+ $strategy = new GenericRetryStrategy(delay: 10.0, maxDelay: 100.0, jitter: 0.1);
+ [$request, $failure] = $this->failure(Method::GET, 503);
+
+ for ($i = 0; $i < 50; ++$i) {
+ $delay = $strategy->getDelay($request, $failure, 1);
+ self::assertNotNull($delay);
+ self::assertGreaterThanOrEqual(9.0, $delay);
+ self::assertLessThanOrEqual(11.0, $delay);
+ }
+ }
+
+ public function test_retry_after_in_seconds_extends_the_delay(): void
+ {
+ self::assertSame(7.0, $this->strategy()->getDelay(...$this->failure(Method::GET, 503, '7')));
+ }
+
+ public function test_retry_after_shorter_than_the_backoff_does_not_shorten_it(): void
+ {
+ self::assertSame(4.0, $this->strategy()->getDelay(...$this->failure(Method::GET, 503, '0', retryCount: 3)));
+ }
+
+ public function test_retry_after_as_http_date(): void
+ {
+ self::assertSame(12.0, $this->strategy()->getDelay(...$this->failure(Method::GET, 429, 'Sun, 25 Oct 2026 12:00:12 GMT')));
+ }
+
+ public function test_unreadable_retry_after_falls_back_to_the_backoff(): void
+ {
+ self::assertSame(1.0, $this->strategy()->getDelay(...$this->failure(Method::GET, 429, 'soon')));
+ }
+
+ public function test_retry_after_beyond_max_delay_gives_up(): void
+ {
+ self::assertNull($this->strategy()->getDelay(...$this->failure(Method::GET, 429, '31')));
+ }
+
+ public function test_custom_status_codes_with_and_without_method_restriction(): void
+ {
+ $strategy = new GenericRetryStrategy([409 => GenericRetryStrategy::IDEMPOTENT_METHODS, 429], jitter: 0.0);
+
+ self::assertNotNull($strategy->getDelay(...$this->failure(Method::PUT, 409)));
+ self::assertNull($strategy->getDelay(...$this->failure(Method::POST, 409)));
+ self::assertNotNull($strategy->getDelay(...$this->failure(Method::POST, 429)));
+ self::assertNull($strategy->getDelay(...$this->failure(Method::GET, 503)));
+ }
+
+ public function test_network_errors_are_retried_for_idempotent_methods_only(): void
+ {
+ $get = new Request(Method::GET, 'items');
+ $post = new Request(Method::POST, 'items');
+
+ self::assertSame(1.0, $this->strategy()->getDelay($get, new TransportException($get, new \RuntimeException()), 1));
+ self::assertNull($this->strategy()->getDelay($post, new TransportException($post, new \RuntimeException()), 1));
+ self::assertNull((new GenericRetryStrategy(retryNetworkErrors: false))->getDelay($get, new TransportException($get, new \RuntimeException()), 1));
+ }
+
+ public function test_malformed_requests_are_never_retried(): void
+ {
+ $get = new Request(Method::GET, 'items');
+ $malformed = new class extends \InvalidArgumentException implements RequestExceptionInterface {
+ public function getRequest(): Psr7RequestInterface
+ {
+ throw new \LogicException('not needed');
+ }
+ };
+
+ self::assertNull($this->strategy()->getDelay($get, new TransportException($get, $malformed), 1));
+ }
+
+ public function test_invalid_configuration_is_rejected(): void
+ {
+ $this->expectException(\InvalidArgumentException::class);
+
+ new GenericRetryStrategy(delay: 10.0, maxDelay: 5.0);
+ }
+
+ private function strategy(float $delay = 1.0, float $multiplier = 2.0, float $maxDelay = 30.0): GenericRetryStrategy
+ {
+ return new GenericRetryStrategy(
+ delay: $delay,
+ multiplier: $multiplier,
+ maxDelay: $maxDelay,
+ jitter: 0.0,
+ clock: new MockClock('2026-10-25 12:00:00 UTC'),
+ );
+ }
+
+ /**
+ * @return array{Request, ResponseException, int}
+ */
+ private function failure(Method $method, int $statusCode, ?string $retryAfter = null, int $retryCount = 1): array
+ {
+ $request = new Request($method, 'items');
+ $headers = null === $retryAfter ? [] : ['Retry-After' => [$retryAfter]];
+
+ return [$request, ResponseException::create($request, new Response('', $statusCode, $headers)), $retryCount];
+ }
+}
diff --git a/src/Api/Retry/RetryStrategyInterface.php b/src/Api/Retry/RetryStrategyInterface.php
new file mode 100644
index 0000000..d2928cc
--- /dev/null
+++ b/src/Api/Retry/RetryStrategyInterface.php
@@ -0,0 +1,19 @@
+retry(
- fn (): ResponseInterface => $this->client->request($request),
- $this->maxRetries,
- $this->addJitter
- );
+ $deadline = null === $this->maxDuration ? null : $this->now() + $this->maxDuration;
+ $retryCount = 0;
+
+ while (true) {
+ try {
+ return $this->client->request($request);
+ } catch (ResponseException|TransportException $failure) {
+ if ($retryCount >= $this->maxRetries) {
+ throw $failure;
+ }
+
+ $delay = $this->strategy->getDelay($request, $failure, ++$retryCount);
+
+ if (null === $delay || (null !== $deadline && $this->now() + $delay >= $deadline)) {
+ throw $failure;
+ }
+
+ $this->clock->sleep($delay);
+ }
+ }
+ }
+
+ private function now(): float
+ {
+ return (float) $this->clock->now()->format('U.u');
}
}
diff --git a/src/Api/RetryClientTest.php b/src/Api/RetryClientTest.php
index 6fb848e..78ea772 100644
--- a/src/Api/RetryClientTest.php
+++ b/src/Api/RetryClientTest.php
@@ -4,57 +4,152 @@
namespace Api;
+use Api\Clock\MockClock;
+use Api\Exception\ResponseException;
use Api\Exception\ServerException;
+use Api\Exception\TransportException;
use Api\Request\Method;
use Api\Request\Request;
-use Api\Request\RequestInterface;
-use Api\Response\ResponseInterface;
+use Api\Response\Response;
+use Api\Retry\GenericRetryStrategy;
+use Api\Testing\MockClient;
+use PHPUnit\Framework\Attributes\CoversClass;
+use PHPUnit\Framework\Attributes\Group;
+use PHPUnit\Framework\Attributes\UsesClass;
use PHPUnit\Framework\TestCase;
-/**
- * @covers \Api\RetryClient
- *
- * @uses \Api\Request\Request
- * @uses \Api\Exception\ResponseException
- * @uses \Api\Exception\ServerException
- *
- * @group integration
- */
+#[CoversClass(RetryClient::class)]
+#[UsesClass(GenericRetryStrategy::class)]
+#[UsesClass(MockClient::class)]
+#[UsesClass(MockClock::class)]
+#[UsesClass(Request::class)]
+#[UsesClass(Response::class)]
+#[UsesClass(Method::class)]
+#[UsesClass(ResponseException::class)]
+#[UsesClass(ServerException::class)]
+#[UsesClass(Exception\ClientException::class)]
+#[UsesClass(TransportException::class)]
+#[UsesClass(Exception\RequestDescription::class)]
+#[Group('unit')]
final class RetryClientTest extends TestCase
{
- public function test_client_is_called_three_times(): void
+ private MockClock $clock;
+
+ protected function setUp(): void
+ {
+ $this->clock = new MockClock('2026-10-25 12:00:00');
+ }
+
+ public function test_a_get_is_retried_on_503_until_it_succeeds(): void
{
- $testRequest = new TestRequest();
- $traceableClient = new TestClient();
- $retryClient = new RetryClient($traceableClient, 3, true);
+ $inner = new MockClient([new Response('', 503), new Response('', 503), new Response('ok', 200)]);
+
+ $response = $this->retryClient($inner)->request(new Request(Method::GET, 'items'));
+
+ self::assertSame('ok', $response->rawBody());
+ self::assertCount(3, $inner->requests());
+ self::assertSame([1.0, 2.0], $this->clock->sleeps());
+ }
+
+ public function test_a_post_is_not_retried_on_503(): void
+ {
+ $inner = new MockClient([new Response('', 503), new Response('ok', 200)]);
try {
- $retryClient->request($testRequest);
- } catch (\Exception) {
- self::assertCount(3, $traceableClient->requests);
+ $this->retryClient($inner)->request(new Request(Method::POST, 'invoices', ['a' => 1]));
+ self::fail('No exception thrown.');
+ } catch (ServerException) {
+ self::assertCount(1, $inner->requests());
+ self::assertSame([], $this->clock->sleeps());
}
}
-}
-final class TestClient implements ClientInterface
-{
- public array $requests = [];
+ public function test_a_post_is_retried_on_429_honouring_retry_after(): void
+ {
+ $inner = new MockClient([new Response('', 429, ['Retry-After' => ['5']]), new Response('ok', 200)]);
+
+ $this->retryClient($inner)->request(new Request(Method::POST, 'invoices', ['a' => 1]));
+
+ self::assertCount(2, $inner->requests());
+ self::assertSame([5.0], $this->clock->sleeps());
+ }
- public function request(RequestInterface $request): ResponseInterface
+ public function test_a_retry_after_beyond_max_delay_is_not_waited_for(): void
{
- $this->requests[] = $request;
+ $inner = new MockClient([new Response('', 429, ['Retry-After' => ['3600']]), new Response('ok', 200)]);
+
+ $this->expectException(ResponseException::class);
+ $this->expectExceptionCode(429);
- throw new ServerException(500, 'retry client test');
+ $this->retryClient($inner)->request(new Request(Method::GET, 'items'));
}
-}
-final class TestRequest extends Request
-{
- public function __construct()
+ public function test_network_errors_are_retried_for_idempotent_methods_only(): void
+ {
+ $failure = static fn (Request $request): TransportException => new TransportException($request, new \RuntimeException('connection reset'));
+
+ $get = new Request(Method::GET, 'items');
+ $inner = new MockClient([$failure($get), new Response('ok', 200)]);
+ self::assertSame('ok', $this->retryClient($inner)->request($get)->rawBody());
+
+ $post = new Request(Method::POST, 'items', ['a' => 1]);
+ $inner = new MockClient([$failure($post), new Response('ok', 200)]);
+ $this->expectException(TransportException::class);
+ $this->retryClient($inner)->request($post);
+ }
+
+ public function test_the_last_failure_is_thrown_once_max_retries_is_reached(): void
+ {
+ $inner = new MockClient([new Response('', 502), new Response('', 503), new Response('', 504)]);
+
+ try {
+ $this->retryClient($inner, maxRetries: 2)->request(new Request(Method::GET, 'items'));
+ self::fail('No exception thrown.');
+ } catch (ServerException $exception) {
+ self::assertSame(504, $exception->getCode());
+ self::assertCount(3, $inner->requests());
+ }
+ }
+
+ public function test_no_retry_is_attempted_past_the_deadline(): void
+ {
+ $inner = new MockClient([new Response('', 503), new Response('', 503), new Response('ok', 200)]);
+
+ try {
+ // first wait 1s fits into 2.5s, the second (2s, ending at 3s) does not
+ $this->retryClient($inner, maxDuration: 2.5)->request(new Request(Method::GET, 'items'));
+ self::fail('No exception thrown.');
+ } catch (ServerException) {
+ self::assertCount(2, $inner->requests());
+ self::assertSame([1.0], $this->clock->sleeps());
+ }
+ }
+
+ public function test_other_exceptions_are_not_retried(): void
+ {
+ $inner = new MockClient([new \LogicException('bug'), new Response('ok', 200)]);
+
+ $this->expectException(\LogicException::class);
+
+ $this->retryClient($inner)->request(new Request(Method::GET, 'items'));
+ }
+
+ public function test_negative_max_retries_are_rejected(): void
+ {
+ $this->expectException(\InvalidArgumentException::class);
+ $this->expectExceptionMessage('maxRetries cannot be negative');
+
+ $this->retryClient(new MockClient(), maxRetries: -1);
+ }
+
+ private function retryClient(MockClient $inner, int $maxRetries = 3, ?float $maxDuration = null): RetryClient
{
- parent::__construct(
- Method::GET,
- '/test'
+ return new RetryClient(
+ $inner,
+ new GenericRetryStrategy(jitter: 0.0, clock: $this->clock),
+ $maxRetries,
+ $maxDuration,
+ $this->clock,
);
}
}
diff --git a/src/Api/RetryTrait.php b/src/Api/RetryTrait.php
deleted file mode 100644
index 20dfc0d..0000000
--- a/src/Api/RetryTrait.php
+++ /dev/null
@@ -1,73 +0,0 @@
-wait($attempt, $addJitter);
-
- try {
- /** @var ResponseInterface $result */
- $result = $callback();
- if (!$result instanceof ResponseInterface) {
- throw new \RuntimeException('return-type of $callback should be of type ResponseInterface');
- }
- } catch (ServerException $serverException) {
- $exception = $serverException;
- }
-
- $retry = ++$attempt;
-
- if ($retry >= $maxRetries && !is_null($exception)) {
- throw $exception;
- }
-
- $try = $retry < $maxRetries && !is_null($exception);
- }
-
- return $result;
- }
-
- private function wait(int $attempt, bool $addJitter): void
- {
- if ($attempt <= 0) {
- return;
- }
-
- // exponential strategy
- $waitTime = (1 + 2 ** $attempt) * 100;
-
- if ($addJitter) {
- // jitter by +/- 25%
- $waitTime *= random_int(75, 125) / 100;
- }
-
- usleep((int) $waitTime * static::getWaitTimeFactor());
- }
-
- private function getWaitTimeFactor(): int
- {
- return 500;
- }
-}
diff --git a/src/Api/RetryTraitTest.php b/src/Api/RetryTraitTest.php
deleted file mode 100644
index b7cef52..0000000
--- a/src/Api/RetryTraitTest.php
+++ /dev/null
@@ -1,156 +0,0 @@
-retry(fn (): ResponseInterface => new SuccessResponse());
- }
- };
-
- self::assertEquals(200, $testRetry->run()->statusCode());
- }
-
- public function test_retry_successful_before_max_attempts_reached(): void
- {
- $testRetry = new class {
- use RetryTrait;
-
- public function run(): ResponseInterface
- {
- $attempt = 0;
-
- return $this->retry(
- function () use (&$attempt): ResponseInterface {
- ++$attempt;
- if ($attempt <= 2) {
- throw new ServerException(500, 'attempts reached');
- }
-
- return new SuccessResponse();
- },
- 3,
- true
- );
- }
-
- private function getWaitTimeFactor(): int
- {
- return 1;
- }
- };
-
- self::assertEquals(200, $testRetry->run()->statusCode());
- }
-
- public function test_retry_throws_exception_after_maximum_retries(): void
- {
- $testRetry = new class {
- use RetryTrait;
-
- public function run(): ResponseInterface
- {
- $attempt = 0;
-
- return $this->retry(
- function () use (&$attempt): ResponseInterface {
- ++$attempt;
- if ($attempt <= 2) {
- throw new \Exception('max attempts reached');
- }
-
- return new SuccessResponse();
- },
- 1,
- true
- );
- }
- };
-
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('max attempts reached');
-
- $testRetry->run();
- }
-
- public function test_retry_re_throws_exception(): void
- {
- $testRetry = new class {
- use RetryTrait;
-
- public function run(): ResponseInterface
- {
- return $this->retry(fn () => throw new \Exception('failure'));
- }
- };
-
- $this->expectException(\Exception::class);
- $this->expectExceptionMessage('failure');
-
- $testRetry->run();
- }
-
- public function test_retry_throws_exception_on_negative_attempts(): void
- {
- $testRetry = new class {
- use RetryTrait;
-
- public function run(): ResponseInterface
- {
- return $this->retry(
- fn (): ResponseInterface => new SuccessResponse(),
- -1,
- true
- );
- }
- };
-
- $this->expectException(\RuntimeException::class);
- $this->expectExceptionMessage('negative');
-
- $testRetry->run();
- }
-}
-
-final class SuccessResponse implements ResponseInterface
-{
- /**
- * @return mixed[]
- */
- public function body(): array
- {
- return [];
- }
-
- public function headers(): array
- {
- return [];
- }
-
- public function statusCode(): int
- {
- return 200;
- }
-}
diff --git a/src/Api/Testing/MockClient.php b/src/Api/Testing/MockClient.php
new file mode 100644
index 0000000..ff26624
--- /dev/null
+++ b/src/Api/Testing/MockClient.php
@@ -0,0 +1,93 @@
+ */
+ private array $queue = [];
+
+ /** @var list */
+ private array $requests = [];
+
+ /**
+ * @param iterable $responses
+ */
+ public function __construct(iterable $responses = [])
+ {
+ $this->append(...$responses);
+ }
+
+ public static function json(mixed $body, int $statusCode = 200): Response
+ {
+ return new Response(
+ json_encode($body, \JSON_THROW_ON_ERROR),
+ $statusCode,
+ ['Content-Type' => ['application/json']],
+ new JsonResponseBodyDecoder(),
+ );
+ }
+
+ public function append(ResponseInterface|\Throwable|\Closure ...$responses): self
+ {
+ foreach ($responses as $response) {
+ $this->queue[] = $response;
+ }
+
+ return $this;
+ }
+
+ public function request(RequestInterface $request): ResponseInterface
+ {
+ $this->requests[] = $request;
+
+ $next = array_shift($this->queue);
+
+ if (null === $next) {
+ throw new \LogicException(sprintf('No response queued for request #%d "%s %s".', \count($this->requests), $request->method(), $request->uri()));
+ }
+
+ if ($next instanceof \Throwable) {
+ throw $next;
+ }
+
+ $response = $next instanceof \Closure ? $next($request) : $next;
+
+ if ($response->statusCode() >= 400) {
+ throw ResponseException::create($request, $response);
+ }
+
+ return $response;
+ }
+
+ /**
+ * @return list
+ */
+ public function requests(): array
+ {
+ return $this->requests;
+ }
+
+ public function hasPendingResponses(): bool
+ {
+ return [] !== $this->queue;
+ }
+}
diff --git a/src/Api/Testing/MockClientTest.php b/src/Api/Testing/MockClientTest.php
new file mode 100644
index 0000000..af4dbb7
--- /dev/null
+++ b/src/Api/Testing/MockClientTest.php
@@ -0,0 +1,65 @@
+ 1]),
+ static fn (RequestInterface $request): Response => new Response($request->uri(), 200),
+ ]);
+
+ self::assertSame(['id' => 1], $client->request(new Request(Method::GET, 'a'))->body());
+ self::assertSame('b', $client->request(new Request(Method::GET, 'b'))->rawBody());
+ self::assertCount(2, $client->requests());
+ self::assertFalse($client->hasPendingResponses());
+ }
+
+ public function test_error_responses_and_exceptions_are_thrown(): void
+ {
+ $client = (new MockClient())->append(MockClient::json(['error' => 'nope'], 404), new \RuntimeException('boom'));
+
+ try {
+ $client->request(new Request(Method::GET, 'a'));
+ self::fail('No exception thrown.');
+ } catch (ClientException $exception) {
+ self::assertSame(404, $exception->getCode());
+ }
+
+ $this->expectExceptionMessage('boom');
+ $client->request(new Request(Method::GET, 'b'));
+ }
+
+ public function test_it_fails_loudly_when_nothing_is_queued(): void
+ {
+ $this->expectException(\LogicException::class);
+ $this->expectExceptionMessage('No response queued for request #1 "GET a"');
+
+ (new MockClient())->request(new Request(Method::GET, 'a'));
+ }
+}