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
34 changes: 34 additions & 0 deletions Tests/HttpOptionHeadersTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?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\Http;
use Joomla\Http\Response;
use Joomla\Http\TransportInterface;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\TestCase;

/**
* Test class for the headers option of Joomla\Http\Http.
*/
#[CoversClass(Http::class)]
class HttpOptionHeadersTest extends TestCase
{
public function testRequestHeaderOverridesOptionHeaderInAnyCase(): void
{
$transport = $this->createMock(TransportInterface::class);
$transport->expects($this->once())
->method('request')
->with('GET', $this->anything(), null, ['accept' => 'application/json', 'X-Option' => 'set'])
->willReturn(new Response());

$http = new Http(['headers' => ['Accept' => 'text/html', 'X-Option' => 'set']], $transport);

$http->get('http://example.com', ['accept' => 'application/json']);
}
}
171 changes: 171 additions & 0 deletions Tests/Transport/HeaderNormalisationTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
<?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\Transport;

use Joomla\Http\AbstractTransport;
use Joomla\Http\Transport\Curl;
use Joomla\Http\Transport\Socket;
use Joomla\Http\Transport\Stream;
use Joomla\Uri\Uri;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;

/**
* Test class for header names in any case and header values given as lists.
*/
#[CoversClass(AbstractTransport::class)]
#[CoversClass(Curl::class)]
#[CoversClass(Socket::class)]
#[CoversClass(Stream::class)]
class HeaderNormalisationTest extends TestCase
{
/**
* Create a transport that exposes the protected header helpers.
*
* @return AbstractTransport
*/
private function createTransport(): AbstractTransport
{
return new class () extends AbstractTransport {
public function request($method, $uri, $data = null, array $headers = [], $timeout = null, $userAgent = null)
{
}

public static function isSupported()
{
return true;
}

public function value(array $headers, string $name): ?string
{
return $this->getHeaderValue($headers, $name);
}

public function set(array $headers, string $name, $value): array
{
return $this->setHeader($headers, $name, $value);
}
};
}

public function testHeaderValueIsFoundInAnyCase(): void
{
$transport = $this->createTransport();

$this->assertSame('application/json', $transport->value(['content-type' => 'application/json'], 'Content-Type'));
$this->assertSame('close', $transport->value(['CONNECTION' => 'close'], 'Connection'));
$this->assertNull($transport->value(['Accept' => 'text/html'], 'Content-Type'));
}

public function testListValuesAreJoined(): void
{
$this->assertSame('gzip, deflate', $this->createTransport()->value(['Accept-Encoding' => ['gzip', 'deflate']], 'accept-encoding'));
}

public function testSetHeaderReplacesTheHeaderInAnyCase(): void
{
$this->assertSame(
['Accept' => 'text/html', 'Content-Length' => 7],
$this->createTransport()->set(['content-length' => 3, 'Accept' => 'text/html'], 'Content-Length', 7)
);
}

public static function transportProvider(): array
{
return [
'curl adapter' => [Curl::class],
'socket adapter' => [Socket::class],
'stream adapter' => [Stream::class],
];
}

/**
* Get the URL of the stub, or skip the test.
*
* @param string $transportClass The transport class to test
*
* @return string
*/
private function getStubUrl(string $transportClass): string
{
if (!$transportClass::isSupported()) {
$this->markTestSkipped(sprintf('The "%s" adapter is not supported in this environment.', $transportClass));
}

if (!\defined('JTEST_HTTP_STUB') && getenv('JTEST_HTTP_STUB') == '') {
$this->markTestSkipped('The Transport test stub has not been configured');
}

return \defined('JTEST_HTTP_STUB') ? JTEST_HTTP_STUB : getenv('JTEST_HTTP_STUB');
}

#[DataProvider('transportProvider')]
public function testLowerCaseContentTypeIsNotOverridden(string $transportClass): void
{
$url = $this->getStubUrl($transportClass);

$response = (new $transportClass([]))->request('POST', new Uri($url), '{"key":"value"}', ['content-type' => 'application/json']);
$headers = array_change_key_case((array) json_decode((string) $response->getBody())->headers);

$this->assertSame('application/json', $headers['content-type']);
}

/**
* Send a request and fail on any PHP warning or notice raised meanwhile.
*
* @param callable $request The request to send.
*
* @return mixed The response.
*/
private function sendWithoutErrors(callable $request)
{
$errors = [];

set_error_handler(
static function (int $severity, string $message) use (&$errors): bool {
$errors[] = $message;

return true;
}
);

try {
$response = $request();
} finally {
restore_error_handler();
}

$this->assertSame([], $errors);

return $response;
}

#[DataProvider('transportProvider')]
public function testListValuedAcceptEncodingIsSent(string $transportClass): void
{
$url = $this->getStubUrl($transportClass);

$response = $this->sendWithoutErrors(
static fn () => (new $transportClass([]))->request('GET', new Uri($url), null, ['Accept-Encoding' => ['identity']])
);

$this->assertSame('identity', json_decode((string) $response->getBody())->http_accept_encoding);
}

public function testListValuedMultipartContentTypeIsUsedByCurl(): void
{
$url = $this->getStubUrl(Curl::class);

$response = $this->sendWithoutErrors(
static fn () => (new Curl([]))->request('POST', new Uri($url), ['key' => 'value'], ['Content-Type' => ['multipart/form-data']])
);

$this->assertSame('value', json_decode((string) $response->getBody())->post->key);
}
}
2 changes: 2 additions & 0 deletions Tests/stubs/jhttp_stub.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@

$response->http_referer = getVar($_SERVER, 'HTTP_REFERER');

$response->headers = function_exists('getallheaders') ? getallheaders() : [];

$response->get = $_GET;
$response->post = $_POST;
$response->files = $_FILES;
Expand Down
4 changes: 3 additions & 1 deletion docs/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,9 @@ $response = $http->trace('http://api.example.com/cars/1');

Custom headers can be passed into each REST request, but they can also be set globally in the constructor options where the
option path starts with "headers.". In the case where a request method passes additional headers, those will override the
headers set in the options.
headers set in the options. Header names are compared case-insensitively, so `accept` in a request
overrides `Accept` in the options, and a `content-type` you pass is not replaced by the transport's
default. A header value may be a string or a list of strings.

```php

Expand Down
45 changes: 45 additions & 0 deletions src/AbstractTransport.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,51 @@ public function __construct($options = [])
$this->options = $options;
}

/**
* Get the value of a request header, ignoring the case of its name.
*
* @param array $headers The request headers, with a string or a list of strings per name.
* @param string $name The name of the header.
*
* @return string|null The value, with list values joined by a comma, or null if the header is not set.
*
* @since __DEPLOY_VERSION__
*/
protected function getHeaderValue(array $headers, string $name): ?string
{
foreach ($headers as $key => $value) {
if (strcasecmp((string) $key, $name) === 0) {
return implode(', ', (array) $value);
}
}

return null;
}

/**
* Set a request header, replacing a header of the same name in any case.
*
* @param array $headers The request headers.
* @param string $name The name of the header.
* @param mixed $value The value of the header.
*
* @return array The request headers.
*
* @since __DEPLOY_VERSION__
*/
protected function setHeader(array $headers, string $name, $value): array
{
foreach (array_keys($headers) as $key) {
if (strcasecmp((string) $key, $name) === 0) {
unset($headers[$key]);
}
}

$headers[$name] = $value;

return $headers;
}

/**
* Get an option from the HTTP transport.
*
Expand Down
5 changes: 4 additions & 1 deletion src/Http.php
Original file line number Diff line number Diff line change
Expand Up @@ -275,8 +275,11 @@ protected function makeTransportRequest($method, $url, $data = null, array $head
if (isset($this->options['headers'])) {
$temp = (array) $this->options['headers'];

// Header names are case-insensitive, so a request header overrides an option header in any case.
$names = array_map('strtolower', array_map('strval', array_keys($headers)));

foreach ($temp as $key => $val) {
if (!isset($headers[$key])) {
if (!\in_array(strtolower((string) $key), $names, true)) {
$headers[$key] = $val;
}
}
Expand Down
14 changes: 9 additions & 5 deletions src/Transport/Curl.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,21 +71,23 @@ public function request($method, UriInterface $uri, $data = null, array $headers

// If data exists let's encode it and make sure our Content-type header is set.
if (isset($data)) {
$contentType = $this->getHeaderValue($headers, 'Content-Type');

// If the data is a scalar value simply add it to the cURL post fields.
if (is_scalar($data) || (isset($headers['Content-Type']) && strpos($headers['Content-Type'], 'multipart/form-data') === 0)) {
if (is_scalar($data) || ($contentType !== null && stripos($contentType, 'multipart/form-data') === 0)) {
$options[\CURLOPT_POSTFIELDS] = $data;
} else {
// Otherwise we need to encode the value first.
$options[\CURLOPT_POSTFIELDS] = http_build_query($data);
}

if (!isset($headers['Content-Type'])) {
if ($contentType === null) {
$headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
}

// Add the relevant headers.
if (is_scalar($options[\CURLOPT_POSTFIELDS])) {
$headers['Content-Length'] = \strlen($options[\CURLOPT_POSTFIELDS]);
$headers = $this->setHeader($headers, 'Content-Length', \strlen($options[\CURLOPT_POSTFIELDS]));
}
}

Expand All @@ -108,8 +110,10 @@ public function request($method, UriInterface $uri, $data = null, array $headers
}

// Curl needs the accepted encoding header as option
if (isset($headers['Accept-Encoding'])) {
$options[\CURLOPT_ENCODING] = $headers['Accept-Encoding'];
$acceptEncoding = $this->getHeaderValue($headers, 'Accept-Encoding');

if ($acceptEncoding !== null) {
$options[\CURLOPT_ENCODING] = $acceptEncoding;
}

// If an explicit timeout is given use it.
Expand Down
8 changes: 4 additions & 4 deletions src/Transport/Socket.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,27 +72,27 @@ public function request($method, UriInterface $uri, $data = null, array $headers
$data = http_build_query($data);
}

if (!isset($headers['Content-Type'])) {
if ($this->getHeaderValue($headers, 'Content-Type') === null) {
$headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
}

// Add the relevant headers.
$headers['Content-Length'] = \strlen($data);
$headers = $this->setHeader($headers, 'Content-Length', \strlen($data));
}

// Configure protocol version, use transport's default if not set otherwise.
$protocolVersion = $this->getOption('protocolVersion', '1.0');

// HTTP/1.1 streams using the socket wrapper require a Connection: close header
if ($protocolVersion == '1.1' && !isset($headers['Connection'])) {
if ($protocolVersion == '1.1' && $this->getHeaderValue($headers, 'Connection') === null) {
$headers['Connection'] = 'close';
}

// Build the request payload.
$request = [];
$request[] = strtoupper($method) . ' ' . ((empty($path)) ? '/' : $path) . ' HTTP/' . $protocolVersion;

if (!isset($headers['Host'])) {
if ($this->getHeaderValue($headers, 'Host') === null) {
$request[] = 'Host: ' . $uri->getHost();
}

Expand Down
6 changes: 3 additions & 3 deletions src/Transport/Stream.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,12 @@ public function request(
$options['content'] = http_build_query($data);
}

if (!isset($headers['Content-Type'])) {
if ($this->getHeaderValue($headers, 'Content-Type') === null) {
$headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
}

// Add the relevant headers.
$headers['Content-Length'] = \strlen($options['content']);
$headers = $this->setHeader($headers, 'Content-Length', \strlen($options['content']));
}

// If an explicit timeout is given user it.
Expand All @@ -90,7 +90,7 @@ public function request(
$options['protocol_version'] = $this->getOption('protocolVersion', '1.0');

// HTTP/1.1 streams using the PHP stream wrapper require a Connection: close header
if ($options['protocol_version'] == '1.1' && !isset($headers['Connection'])) {
if ($options['protocol_version'] == '1.1' && $this->getHeaderValue($headers, 'Connection') === null) {
$headers['Connection'] = 'close';
}

Expand Down
Loading