diff --git a/Tests/HttpSendRequestTest.php b/Tests/HttpSendRequestTest.php new file mode 100644 index 00000000..669f5323 --- /dev/null +++ b/Tests/HttpSendRequestTest.php @@ -0,0 +1,126 @@ +write($body); + + return new Request('http://example.com', 'POST', $stream); + } + + /** + * Create a client whose transport expects the given request data. + * + * @param mixed $data The data the transport must receive. + * + * @return Http + */ + private function createClientExpectingData($data): Http + { + $transport = $this->createMock(TransportInterface::class); + $transport->expects($this->once()) + ->method('request') + ->with('POST', $this->anything(), $this->identicalTo($data)) + ->willReturn(new Response()); + + return new Http([], $transport); + } + + public function testBodyIsSentFromTheStartOfTheStream(): void + { + // Writing leaves the stream at its end, as does reading it. + $request = $this->createRequest('key=value'); + + $this->createClientExpectingData('key=value')->sendRequest($request); + } + + public function testBodyThatWasAlreadyReadIsSentCompletely(): void + { + $request = $this->createRequest('key=value'); + $request->getBody()->rewind(); + $request->getBody()->getContents(); + + $this->createClientExpectingData('key=value')->sendRequest($request); + } + + public function testBodyZeroIsSent(): void + { + $this->createClientExpectingData('0')->sendRequest($this->createRequest('0')); + } + + public function testEmptyBodyIsSentAsNoData(): void + { + $this->createClientExpectingData(null)->sendRequest($this->createRequest('')); + } + + public function testTransportFailureIsThrownAsNetworkException(): void + { + $failure = new \RuntimeException('Could not connect', 7); + $transport = $this->createMock(TransportInterface::class); + $transport->expects($this->once()) + ->method('request') + ->willThrowException($failure); + + $request = $this->createRequest(''); + + try { + (new Http([], $transport))->sendRequest($request); + $this->fail('A NetworkException was expected.'); + } catch (NetworkException $e) { + $this->assertInstanceOf(NetworkExceptionInterface::class, $e); + $this->assertInstanceOf(\RuntimeException::class, $e, 'The exception must stay a RuntimeException for existing callers.'); + $this->assertSame($request, $e->getRequest()); + $this->assertSame('Could not connect', $e->getMessage()); + $this->assertSame(7, $e->getCode()); + $this->assertSame($failure, $e->getPrevious()); + } + } + + public function testClientExceptionsAreNotWrapped(): void + { + $failure = new InvalidResponseCodeException('No HTTP response code found.'); + $transport = $this->createMock(TransportInterface::class); + $transport->expects($this->once()) + ->method('request') + ->willThrowException($failure); + + try { + (new Http([], $transport))->sendRequest($this->createRequest('')); + $this->fail('An exception was expected.'); + } catch (\Exception $e) { + $this->assertSame($failure, $e); + } + } +} diff --git a/docs/classes/Http.md b/docs/classes/Http.md index 80777e03..88f70f6c 100644 --- a/docs/classes/Http.md +++ b/docs/classes/Http.md @@ -21,3 +21,27 @@ $transport = new StreamTransport($options); // Create a 'stream' transport. $http = new Http($options, $transport); ``` + +### Sending a PSR-7 request + +`sendRequest()` implements the PSR-18 `ClientInterface`. The whole request body is sent, even if its stream +was already read, and an empty body is sent as no data. The request's protocol version is not used; the +transport's `protocolVersion` option decides. + +```php +use Laminas\Diactoros\Request; +use Psr\Http\Client\ClientExceptionInterface; +use Psr\Http\Client\NetworkExceptionInterface; + +try { + $response = $http->sendRequest(new Request('https://api.example.com/cars', 'GET')); +} catch (NetworkExceptionInterface $e) { + // No response: the connection failed or was interrupted. $e->getRequest() is the request. +} catch (ClientExceptionInterface $e) { + // Any other failure, such as a response without a status code. +} +``` + +Transport failures are thrown as `Joomla\Http\Exception\NetworkException`, which implements +`NetworkExceptionInterface` and still extends `RuntimeException`, so existing `catch (\RuntimeException $e)` +blocks keep working. diff --git a/src/Exception/NetworkException.php b/src/Exception/NetworkException.php new file mode 100644 index 00000000..b96314a4 --- /dev/null +++ b/src/Exception/NetworkException.php @@ -0,0 +1,58 @@ +request = $request; + } + + /** + * Get the request that failed. + * + * @return RequestInterface + * + * @since __DEPLOY_VERSION__ + */ + public function getRequest(): RequestInterface + { + return $this->request; + } +} diff --git a/src/Http.php b/src/Http.php index cec18620..3c476ea9 100644 --- a/src/Http.php +++ b/src/Http.php @@ -9,8 +9,10 @@ namespace Joomla\Http; +use Joomla\Http\Exception\NetworkException; use Joomla\Uri\Uri; use Joomla\Uri\UriInterface; +use Psr\Http\Client\ClientExceptionInterface; use Psr\Http\Client\ClientInterface; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; @@ -242,17 +244,26 @@ public function patch($url, $data, array $headers = [], $timeout = null) * @return ResponseInterface|Response * * @since 2.0.0 + * @throws ClientExceptionInterface + * @throws NetworkException If the request could not be completed, for example because the connection failed. */ public function sendRequest(RequestInterface $request): ResponseInterface { - $data = $request->getBody()->getContents(); + // Casting the stream rewinds it, so a body that was already read is still sent completely. + $data = (string) $request->getBody(); - return $this->makeTransportRequest( - $request->getMethod(), - new Uri((string) $request->getUri()), - empty($data) ? null : $data, - $request->getHeaders() - ); + try { + return $this->makeTransportRequest( + $request->getMethod(), + new Uri((string) $request->getUri()), + $data === '' ? null : $data, + $request->getHeaders() + ); + } catch (ClientExceptionInterface $e) { + throw $e; + } catch (\RuntimeException $e) { + throw new NetworkException($request, $e->getMessage(), $e->getCode(), $e); + } } /**