Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
8 / 8 |
|
100.00% |
3 / 3 |
CRAP | |
100.00% |
1 / 1 |
| FakeHttpClient | |
100.00% |
8 / 8 |
|
100.00% |
3 / 3 |
5 | |
100.00% |
1 / 1 |
| queue | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
| lastRequest | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| sendRequest | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
3 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace LambdaTwelve\OneRecord\Testing; |
| 6 | |
| 7 | use Closure; |
| 8 | use LogicException; |
| 9 | use Psr\Http\Client\ClientExceptionInterface; |
| 10 | use Psr\Http\Client\ClientInterface; |
| 11 | use Psr\Http\Message\RequestInterface; |
| 12 | use Psr\Http\Message\ResponseInterface; |
| 13 | |
| 14 | /** |
| 15 | * A PSR-18 client answering from a queue or a callable; records every request. |
| 16 | */ |
| 17 | final class FakeHttpClient implements ClientInterface |
| 18 | { |
| 19 | /** @var list<RequestInterface> */ |
| 20 | public array $requests = []; |
| 21 | |
| 22 | /** @var list<ResponseInterface|Closure(RequestInterface): ResponseInterface|ClientExceptionInterface> */ |
| 23 | private array $queue = []; |
| 24 | |
| 25 | /** |
| 26 | * @param ResponseInterface|Closure(RequestInterface): ResponseInterface|ClientExceptionInterface $response |
| 27 | */ |
| 28 | public function queue(ResponseInterface|Closure|ClientExceptionInterface $response): self |
| 29 | { |
| 30 | $this->queue[] = $response; |
| 31 | |
| 32 | return $this; |
| 33 | } |
| 34 | |
| 35 | /** |
| 36 | * The most recent request, for assertions after a single call. |
| 37 | */ |
| 38 | public function lastRequest(): RequestInterface |
| 39 | { |
| 40 | return $this->requests[array_key_last($this->requests) ?? throw new LogicException('No request was sent.')]; |
| 41 | } |
| 42 | |
| 43 | public function sendRequest(RequestInterface $request): ResponseInterface |
| 44 | { |
| 45 | $this->requests[] = $request; |
| 46 | $next = array_shift($this->queue) ?? throw new LogicException('No response queued for ' . $request->getMethod() . ' ' . $request->getUri()); |
| 47 | if ($next instanceof ClientExceptionInterface) { |
| 48 | throw $next; |
| 49 | } |
| 50 | |
| 51 | return $next instanceof Closure ? $next($request) : $next; |
| 52 | } |
| 53 | } |