|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Http\Adapter\Mock; |
| 4 | + |
| 5 | +use Http\Client\Common\HttpAsyncClientEmulator; |
| 6 | +use Http\Client\HttpAsyncClient; |
| 7 | +use Http\Client\HttpClient; |
| 8 | +use Http\Discovery\MessageFactoryDiscovery; |
| 9 | +use Psr\Http\Message\RequestInterface; |
| 10 | +use Psr\Http\Message\ResponseInterface; |
| 11 | + |
| 12 | +/** |
| 13 | + * HTTP client mock |
| 14 | + * |
| 15 | + * This mock is most useful in tests. It does not send requests but stores them |
| 16 | + * for later retrieval. Additionally, you can set an exception to test |
| 17 | + * exception handling. |
| 18 | + * |
| 19 | + * @author David de Boer <[email protected]> |
| 20 | + */ |
| 21 | +class Client implements HttpClient, HttpAsyncClient |
| 22 | +{ |
| 23 | + use HttpAsyncClientEmulator; |
| 24 | + |
| 25 | + private $requests = []; |
| 26 | + private $responses = []; |
| 27 | + private $exceptions = []; |
| 28 | + |
| 29 | + /** |
| 30 | + * {@inheritdoc} |
| 31 | + */ |
| 32 | + public function sendRequest(RequestInterface $request) |
| 33 | + { |
| 34 | + $this->requests[] = $request; |
| 35 | + |
| 36 | + if (count($this->exceptions) > 0) { |
| 37 | + throw array_shift($this->exceptions); |
| 38 | + } |
| 39 | + |
| 40 | + if (count($this->responses) > 0) { |
| 41 | + return array_shift($this->responses); |
| 42 | + } |
| 43 | + |
| 44 | + // Return success response by default |
| 45 | + return MessageFactoryDiscovery::find()->createResponse(); |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * Add exception that will be thrown |
| 50 | + * |
| 51 | + * @param \Exception $exception |
| 52 | + */ |
| 53 | + public function addException(\Exception $exception) |
| 54 | + { |
| 55 | + $this->exceptions[] = $exception; |
| 56 | + } |
| 57 | + |
| 58 | + /** |
| 59 | + * Add response that will be returned |
| 60 | + * |
| 61 | + * @param ResponseInterface $response |
| 62 | + */ |
| 63 | + public function addResponse(ResponseInterface $response) |
| 64 | + { |
| 65 | + $this->responses[] = $response; |
| 66 | + } |
| 67 | + |
| 68 | + /** |
| 69 | + * Get requests that were sent |
| 70 | + * |
| 71 | + * @return RequestInterface[] |
| 72 | + */ |
| 73 | + public function getRequests() |
| 74 | + { |
| 75 | + return $this->requests; |
| 76 | + } |
| 77 | +} |
0 commit comments