From a2b8dd1ad7e733d50e9c7b80cb375e0883a7088d Mon Sep 17 00:00:00 2001 From: Tobias Nyholm Date: Sat, 17 Jul 2021 15:23:23 -0700 Subject: [PATCH] Throw exception if you are using all wrong headers (#2916) --- src/Client.php | 4 ++++ tests/ClientTest.php | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/src/Client.php b/src/Client.php index 7349ec05f..81f4f6dee 100644 --- a/src/Client.php +++ b/src/Client.php @@ -5,6 +5,7 @@ use GuzzleHttp\Cookie\CookieJar; use GuzzleHttp\Exception\GuzzleException; use GuzzleHttp\Exception\InvalidArgumentException; +use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Promise as P; use GuzzleHttp\Promise\PromiseInterface; use Psr\Http\Message\RequestInterface; @@ -344,6 +345,9 @@ private function applyOptions(RequestInterface $request, array &$options): Reque ]; if (isset($options['headers'])) { + if (array_keys($options['headers']) === range(0, count($options['headers']) - 1)) { + throw new RequestException('The headers array must have header name as keys.', $request); + } $modify['set_headers'] = $options['headers']; unset($options['headers']); } diff --git a/tests/ClientTest.php b/tests/ClientTest.php index 8cd13a45d..6817cbd0a 100644 --- a/tests/ClientTest.php +++ b/tests/ClientTest.php @@ -4,6 +4,7 @@ use GuzzleHttp\Client; use GuzzleHttp\Cookie\CookieJar; +use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Handler\MockHandler; use GuzzleHttp\HandlerStack; use GuzzleHttp\Middleware; @@ -613,6 +614,26 @@ public function testSendSendsWithSync() self::assertTrue($mock->getLastOptions()['synchronous']); } + public function testSendWithInvalidHeader() + { + $mock = new MockHandler([new Response()]); + $client = new Client(['handler' => $mock]); + $request = new Request('GET', 'http://foo.com'); + + $this->expectException(RequestException::class); + $client->send($request, ['headers'=>['X-Foo: Bar']]); + } + + public function testSendWithInvalidHeaders() + { + $mock = new MockHandler([new Response()]); + $client = new Client(['handler' => $mock]); + $request = new Request('GET', 'http://foo.com'); + + $this->expectException(RequestException::class); + $client->send($request, ['headers'=>['X-Foo: Bar', 'X-Test: Fail']]); + } + public function testCanSetCustomHandler() { $mock = new MockHandler([new Response(500)]);