From e3cd73439058b191bf5d3bbf965e2194d4d530ec Mon Sep 17 00:00:00 2001 From: sschmitz Date: Fri, 24 Jun 2022 13:10:00 +0200 Subject: [PATCH] added browser property headers to be able to change the headers with the methods withHeader and withoutHeader --- src/Browser.php | 34 +++++++++++++++++++++++++++++++++- tests/BrowserTest.php | 13 +++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/src/Browser.php b/src/Browser.php index 72847f66..c70e8e9d 100644 --- a/src/Browser.php +++ b/src/Browser.php @@ -23,6 +23,7 @@ class Browser private $transaction; private $baseUrl; private $protocolVersion = '1.1'; + private $headers = array(); /** * The `Browser` is responsible for sending HTTP requests to your HTTP server @@ -725,6 +726,32 @@ public function withResponseBuffer($maximumSize) )); } + /** + * @param $header + * @param $value + * @return Browser + *@todo documentation + * + */ + public function withHeader($header, $value) + { + $browser = clone $this; + $browser->headers[$header] = $value; + + return $browser; + } + + public function withoutHeader($header) + { + $browser = clone $this; + + if (array_key_exists($header, $browser->headers)) { + unset($browser->headers[$header]); + } + + return $browser; + } + /** * Changes the [options](#options) to use: * @@ -784,7 +811,12 @@ private function requestMayBeStreaming($method, $url, array $headers = array(), } return $this->transaction->send( - new Request($method, $url, $headers, $body, $this->protocolVersion) + new Request($method, $url, $this->mergeHeaders($headers), $body, $this->protocolVersion) ); } + + private function mergeHeaders(array $headers) + { + return array_merge($headers, $this->headers); + } } diff --git a/tests/BrowserTest.php b/tests/BrowserTest.php index 39be453a..8019d967 100644 --- a/tests/BrowserTest.php +++ b/tests/BrowserTest.php @@ -503,4 +503,17 @@ public function testCancelGetRequestShouldCancelUnderlyingSocketConnection() $promise = $this->browser->get('http://example.com/'); $promise->cancel(); } + + public function testWithElseHeader() + { + $this->browser = $this->browser->withHeader('User-Agent', 'ACMC'); + + $that = $this; + $this->sender->expects($this->once())->method('send')->with($this->callback(function (RequestInterface $request) use ($that) { + $that->assertEquals('ACMC', $request->getHeader('User-Agent')); + return true; + }))->willReturn(new Promise(function () { })); + + $this->browser->get('http://example.com/'); + } }