Skip to content
Open
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
126 changes: 126 additions & 0 deletions Tests/HttpSendRequestTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
<?php

/**
* @copyright Copyright (C) 2005 - 2026 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/

namespace Joomla\Http\Tests;

use Joomla\Http\Exception\InvalidResponseCodeException;
use Joomla\Http\Exception\NetworkException;
use Joomla\Http\Http;
use Joomla\Http\Response;
use Joomla\Http\TransportInterface;
use Laminas\Diactoros\Request;
use Laminas\Diactoros\Stream;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\TestCase;
use Psr\Http\Client\NetworkExceptionInterface;

/**
* Test class for Joomla\Http\Http::sendRequest().
*/
#[CoversClass(Http::class)]
#[CoversClass(NetworkException::class)]
class HttpSendRequestTest extends TestCase
{
/**
* Create a POST request with the given body.
*
* @param string $body The request body.
*
* @return Request
*/
private function createRequest(string $body): Request
{
$stream = new Stream('php://memory', 'rw');
$stream->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);
}
}
}
24 changes: 24 additions & 0 deletions docs/classes/Http.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
58 changes: 58 additions & 0 deletions src/Exception/NetworkException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php

/**
* Part of the Joomla Framework Http Package
*
* @copyright Copyright (C) 2005 - 2026 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/

namespace Joomla\Http\Exception;

use Psr\Http\Client\NetworkExceptionInterface;
use Psr\Http\Message\RequestInterface;

/**
* Exception thrown by Http::sendRequest() when a request could not be completed, for example because the connection failed
*
* @since __DEPLOY_VERSION__
*/
class NetworkException extends \RuntimeException implements NetworkExceptionInterface
{
/**
* The request that failed.
*
* @var RequestInterface
* @since __DEPLOY_VERSION__
*/
private RequestInterface $request;

/**
* Constructor
*
* @param RequestInterface $request The request that failed.
* @param string $message The Exception message to throw.
* @param integer $code The Exception code.
* @param ?\Throwable $previous The previous exception used for the exception chaining.
*
* @since __DEPLOY_VERSION__
*/
public function __construct(RequestInterface $request, string $message = '', int $code = 0, ?\Throwable $previous = null)
{
parent::__construct($message, $code, $previous);

$this->request = $request;
}

/**
* Get the request that failed.
*
* @return RequestInterface
*
* @since __DEPLOY_VERSION__
*/
public function getRequest(): RequestInterface
{
return $this->request;
}
}
25 changes: 18 additions & 7 deletions src/Http.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
}
}

/**
Expand Down
Loading