From 70bf371a765f0d733bfd9cd3506b96e09d2ca5ad Mon Sep 17 00:00:00 2001 From: Hannes Papenberg Date: Fri, 13 Nov 2026 00:05:36 +0100 Subject: [PATCH] Look up request headers case-insensitively and accept list values The transports checked for Content-Type, Content-Length, Connection and Host with isset() on the exact spelling, so a "content-type" passed by the caller got a second, form-encoded Content-Type added, and a lower-case "host" produced two Host headers in the socket transport. The headers option of Http was merged the same way. Header values from sendRequest() are lists. The cURL transport used the raw value for CURLOPT_ENCODING ("Array to string conversion", encoding "Array") and passed it to strpos() for the multipart check (TypeError). Look up headers case-insensitively, replace Content-Length in any case, and join list values before using them for cURL options. Co-Authored-By: Claude Opus 5.5 --- Tests/HttpOptionHeadersTest.php | 34 ++++ Tests/Transport/HeaderNormalisationTest.php | 171 ++++++++++++++++++++ Tests/stubs/jhttp_stub.php | 2 + docs/overview.md | 4 +- src/AbstractTransport.php | 45 ++++++ src/Http.php | 5 +- src/Transport/Curl.php | 14 +- src/Transport/Socket.php | 8 +- src/Transport/Stream.php | 6 +- 9 files changed, 275 insertions(+), 14 deletions(-) create mode 100644 Tests/HttpOptionHeadersTest.php create mode 100644 Tests/Transport/HeaderNormalisationTest.php diff --git a/Tests/HttpOptionHeadersTest.php b/Tests/HttpOptionHeadersTest.php new file mode 100644 index 00000000..c2176b23 --- /dev/null +++ b/Tests/HttpOptionHeadersTest.php @@ -0,0 +1,34 @@ +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']); + } +} diff --git a/Tests/Transport/HeaderNormalisationTest.php b/Tests/Transport/HeaderNormalisationTest.php new file mode 100644 index 00000000..d9a78a10 --- /dev/null +++ b/Tests/Transport/HeaderNormalisationTest.php @@ -0,0 +1,171 @@ +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); + } +} diff --git a/Tests/stubs/jhttp_stub.php b/Tests/stubs/jhttp_stub.php index b3b9a98e..e071f92e 100644 --- a/Tests/stubs/jhttp_stub.php +++ b/Tests/stubs/jhttp_stub.php @@ -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; diff --git a/docs/overview.md b/docs/overview.md index b49bb6d1..8e854315 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -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 diff --git a/src/AbstractTransport.php b/src/AbstractTransport.php index 2dcde7ac..535af7e8 100644 --- a/src/AbstractTransport.php +++ b/src/AbstractTransport.php @@ -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. * diff --git a/src/Http.php b/src/Http.php index cec18620..e0aedeff 100644 --- a/src/Http.php +++ b/src/Http.php @@ -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; } } diff --git a/src/Transport/Curl.php b/src/Transport/Curl.php index 88a8b6c8..fbfc6326 100644 --- a/src/Transport/Curl.php +++ b/src/Transport/Curl.php @@ -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])); } } @@ -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. diff --git a/src/Transport/Socket.php b/src/Transport/Socket.php index 9aedd4c8..399e34c4 100644 --- a/src/Transport/Socket.php +++ b/src/Transport/Socket.php @@ -72,19 +72,19 @@ 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'; } @@ -92,7 +92,7 @@ public function request($method, UriInterface $uri, $data = null, array $headers $request = []; $request[] = strtoupper($method) . ' ' . ((empty($path)) ? '/' : $path) . ' HTTP/' . $protocolVersion; - if (!isset($headers['Host'])) { + if ($this->getHeaderValue($headers, 'Host') === null) { $request[] = 'Host: ' . $uri->getHost(); } diff --git a/src/Transport/Stream.php b/src/Transport/Stream.php index ef468ba0..3a3887e2 100644 --- a/src/Transport/Stream.php +++ b/src/Transport/Stream.php @@ -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. @@ -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'; }