diff --git a/Tests/HttpUserAgentTest.php b/Tests/HttpUserAgentTest.php new file mode 100644 index 00000000..e2d8b540 --- /dev/null +++ b/Tests/HttpUserAgentTest.php @@ -0,0 +1,60 @@ +createMock(TransportInterface::class); + $transport->expects($this->once()) + ->method('request') + ->with('GET', $this->anything(), null, [], null, $userAgent) + ->willReturn(new Response()); + + return $transport; + } + + public function testDefaultUserAgentIsSentByAClientCreatedDirectly(): void + { + (new Http([], $this->createTransportExpectingUserAgent('Mozilla/5.0 Joomla!/Framework')))->get('http://example.com'); + } + + public function testConfiguredUserAgentIsSent(): void + { + (new Http(['userAgent' => 'MyApp/1.0'], $this->createTransportExpectingUserAgent('MyApp/1.0')))->get('http://example.com'); + } + + public function testFactoryDoesNotChangeTheOptionsObject(): void + { + $options = new \ArrayObject(['timeout' => 5]); + + (new HttpFactory())->getHttp($options); + + $this->assertSame(['timeout' => 5], $options->getArrayCopy()); + } +} diff --git a/docs/classes/HttpFactory.md b/docs/classes/HttpFactory.md index 1003805e..b7d4a26a 100644 --- a/docs/classes/HttpFactory.md +++ b/docs/classes/HttpFactory.md @@ -33,6 +33,10 @@ Note that an `InvalidArgumentException` is thrown if the `$options` argument is Note that a `RuntimeException` is thrown if no `Joomla\Http\TransportInterface` objects are available for use. +Requests are sent with the user agent `Mozilla/5.0 Joomla!/Framework` unless the `userAgent` option sets another +one. `Http` applies this default itself, so it also holds for a client created with `new Http()`, and the options +array or object you pass in is not modified. + ### Retrieving a Joomla\Http\TransportInterface object The `getAvailableDriver()` method can be used to create [TransportInterface](TransportInterface.md) objects from the factory. diff --git a/src/Http.php b/src/Http.php index cec18620..6e003f4e 100644 --- a/src/Http.php +++ b/src/Http.php @@ -287,7 +287,8 @@ protected function makeTransportRequest($method, $url, $data = null, array $head $timeout = $this->options['timeout']; } - $userAgent = isset($this->options['userAgent']) ? $this->options['userAgent'] : null; + // Send the default user agent unless one is configured; the options are not changed. + $userAgent = $this->options['userAgent'] ?? 'Mozilla/5.0 Joomla!/Framework'; // Convert to a Uri object if we were given a string if (\is_string($url)) { diff --git a/src/HttpFactory.php b/src/HttpFactory.php index b5ccb726..6e81cb83 100644 --- a/src/HttpFactory.php +++ b/src/HttpFactory.php @@ -36,11 +36,6 @@ public function getHttp($options = [], $adapters = null) ); } - // Set default userAgent if nothing else is set - if (!isset($options['userAgent'])) { - $options['userAgent'] = 'Mozilla/5.0 Joomla!/Framework'; - } - if (!$driver = $this->getAvailableDriver($options, $adapters)) { throw new \RuntimeException('No transport driver available.'); }