Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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"
Expand All @@ -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' ]

Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
.php-cs-fixer.cache
.phpunit.cache
.phpunit.result.cache
phpunit.xml
composer.lock
Expand Down
9 changes: 4 additions & 5 deletions .php-cs-fixer.dist.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'],
])
Expand Down
2 changes: 1 addition & 1 deletion .phpstan/baseline.neon
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
parameters:
ignoreErrors:
ignoreErrors: []
1 change: 0 additions & 1 deletion .phpstan/config.neon
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ parameters:

level: max

checkMissingIterableValueType: false
reportUnmatchedIgnoredErrors: true
treatPhpDocTypesAsCertain: false

Expand Down
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
164 changes: 157 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<a href="https://github.com/jschaedl/api-client/actions">
<img src="https://github.com/jschaedl/api-client/actions/workflows/ci.yaml/badge.svg" alt="ci status">
</a>
<img src="https://img.shields.io/badge/php-8.2%2B-lightblue.svg" alt="php-8.2%2B">
<img src="https://img.shields.io/badge/php-8.2%20to%208.5-lightblue.svg" alt="php-8.2 to 8.5">
<a href="https://packagist.org/packages/jschaedl/api-client">
<img src="https://poser.pugx.org/jschaedl/api-client/v/stable" alt="latest version">
</a>
Expand Down Expand Up @@ -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).

---

Expand Down
61 changes: 61 additions & 0 deletions UPGRADE-0.1.md
Original file line number Diff line number Diff line change
@@ -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.
Loading
Loading