Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 8da7686

Browse filesBrowse files
committed
feature #30843 [HttpClient] Add ScopingHttpClient::forBaseUri() + tweak MockHttpClient (nicolas-grekas)
This PR was merged into the 4.3-dev branch. Discussion ---------- [HttpClient] Add ScopingHttpClient::forBaseUri() + tweak MockHttpClient | Q | A | ------------- | --- | Branch? | master | Bug fix? | no | New feature? | yes | BC breaks? | no | Deprecations? | no | Tests pass? | yes | Fixed tickets | - | License | MIT | Doc PR | - This allows creating scoped HTTP clients in one line: ```php $client = ScopingHttpClient::forBaseUri($client, 'http://example.com'); ``` `$client` now resolves relative URLs using the provided base URI. If one also adds default options as 3rd argument, these will be applied conditionally when a URL matching the base URI is requested. This PR also tweaks `MockHttpClient` to make it return `MockResponse` on its own when no constructor argument is provided, easing tests a bit. Commits ------- 2b9b8e5 [HttpClient] Add ScopingHttpClient::forBaseUri() + tweak MockHttpClient
2 parents 78afdd1 + 2b9b8e5 commit 8da7686
Copy full SHA for 8da7686

File tree

4 files changed

+38
-16
lines changed
Filter options

4 files changed

+38
-16
lines changed

‎src/Symfony/Component/HttpClient/MockHttpClient.php

Copy file name to clipboardExpand all lines: src/Symfony/Component/HttpClient/MockHttpClient.php
+7-5Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,16 +31,16 @@ class MockHttpClient implements HttpClientInterface
3131
private $baseUri;
3232

3333
/**
34-
* @param callable|ResponseInterface|ResponseInterface[]|iterable $responseFactory
34+
* @param callable|ResponseInterface|ResponseInterface[]|iterable|null $responseFactory
3535
*/
36-
public function __construct($responseFactory, string $baseUri = null)
36+
public function __construct($responseFactory = null, string $baseUri = null)
3737
{
3838
if ($responseFactory instanceof ResponseInterface) {
3939
$responseFactory = [$responseFactory];
4040
}
4141

42-
if (!\is_callable($responseFactory) && !$responseFactory instanceof \Iterator) {
43-
$responseFactory = (function () use ($responseFactory) {
42+
if (null !== $responseFactory && !\is_callable($responseFactory) && !$responseFactory instanceof \Iterator) {
43+
$responseFactory = (static function () use ($responseFactory) {
4444
yield from $responseFactory;
4545
})();
4646
}
@@ -57,7 +57,9 @@ public function request(string $method, string $url, array $options = []): Respo
5757
[$url, $options] = $this->prepareRequest($method, $url, $options, ['base_uri' => $this->baseUri], true);
5858
$url = implode('', $url);
5959

60-
if (\is_callable($this->responseFactory)) {
60+
if (null === $this->responseFactory) {
61+
$response = new MockResponse();
62+
} elseif (\is_callable($this->responseFactory)) {
6163
$response = ($this->responseFactory)($method, $url, $options);
6264
} elseif (!$this->responseFactory->valid()) {
6365
throw new TransportException('The response factory iterator passed to MockHttpClient is empty.');

‎src/Symfony/Component/HttpClient/Response/MockResponse.php

Copy file name to clipboardExpand all lines: src/Symfony/Component/HttpClient/Response/MockResponse.php
+4Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,10 @@ public static function fromRequest(string $method, string $url, array $options,
111111
$response->info['user_data'] = $options['user_data'] ?? null;
112112
$response->info['url'] = $url;
113113

114+
if ($mock instanceof self) {
115+
$mock->requestOptions = $response->requestOptions;
116+
}
117+
114118
self::writeRequest($response, $options, $mock);
115119
$response->body[] = [$options, $mock];
116120

‎src/Symfony/Component/HttpClient/ScopingHttpClient.php

Copy file name to clipboardExpand all lines: src/Symfony/Component/HttpClient/ScopingHttpClient.php
+11Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,17 @@ public function __construct(HttpClientInterface $client, array $defaultOptionsBy
3838
$this->defaultRegexp = $defaultRegexp;
3939
}
4040

41+
public static function forBaseUri(HttpClientInterface $client, string $baseUri, array $defaultOptions = [], $regexp = null): self
42+
{
43+
if (null === $regexp) {
44+
$regexp = preg_quote(implode('', self::resolveUrl(self::parseUrl('.'), self::parseUrl($baseUri))));
45+
}
46+
47+
$defaultOptions['base_uri'] = $baseUri;
48+
49+
return new self($client, [$regexp => $defaultOptions], $regexp);
50+
}
51+
4152
/**
4253
* {@inheritdoc}
4354
*/

‎src/Symfony/Component/HttpClient/Tests/ScopingHttpClientTest.php

Copy file name to clipboardExpand all lines: src/Symfony/Component/HttpClient/Tests/ScopingHttpClientTest.php
+16-11Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,13 @@
1414
use PHPUnit\Framework\TestCase;
1515
use Symfony\Component\HttpClient\Exception\InvalidArgumentException;
1616
use Symfony\Component\HttpClient\MockHttpClient;
17-
use Symfony\Component\HttpClient\Response\MockResponse;
1817
use Symfony\Component\HttpClient\ScopingHttpClient;
1918

2019
class ScopingHttpClientTest extends TestCase
2120
{
2221
public function testRelativeUrl()
2322
{
24-
$mockClient = new MockHttpClient([]);
23+
$mockClient = new MockHttpClient();
2524
$client = new ScopingHttpClient($mockClient, []);
2625

2726
$this->expectException(InvalidArgumentException::class);
@@ -30,7 +29,7 @@ public function testRelativeUrl()
3029

3130
public function testRelativeUrlWithDefaultRegexp()
3231
{
33-
$mockClient = new MockHttpClient(new MockResponse());
32+
$mockClient = new MockHttpClient();
3433
$client = new ScopingHttpClient($mockClient, ['.*' => ['base_uri' => 'http://example.com']], '.*');
3534

3635
$this->assertSame('http://example.com/foo', $client->request('GET', '/foo')->getInfo('url'));
@@ -41,7 +40,7 @@ public function testRelativeUrlWithDefaultRegexp()
4140
*/
4241
public function testMatchingUrls(string $regexp, string $url, array $options)
4342
{
44-
$mockClient = new MockHttpClient(new MockResponse());
43+
$mockClient = new MockHttpClient();
4544
$client = new ScopingHttpClient($mockClient, $options);
4645

4746
$response = $client->request('GET', $url);
@@ -69,13 +68,7 @@ public function testMatchingUrlsAndOptions()
6968
'.*' => ['headers' => ['content-type' => 'text/html']],
7069
];
7170

72-
$mockResponses = [
73-
new MockResponse(),
74-
new MockResponse(),
75-
new MockResponse(),
76-
];
77-
78-
$mockClient = new MockHttpClient($mockResponses);
71+
$mockClient = new MockHttpClient();
7972
$client = new ScopingHttpClient($mockClient, $defaultOptions);
8073

8174
$response = $client->request('GET', 'http://example.com/foo-bar', ['json' => ['url' => 'http://example.com']]);
@@ -93,4 +86,16 @@ public function testMatchingUrlsAndOptions()
9386
$this->assertEquals($requestOptions['headers']['x-app'][0], 'unit-test');
9487
$this->assertEquals($requestOptions['headers']['content-type'][0], 'text/html');
9588
}
89+
90+
public function testForBaseUri()
91+
{
92+
$client = ScopingHttpClient::forBaseUri(new MockHttpClient(), 'http://example.com/foo');
93+
94+
$response = $client->request('GET', '/bar');
95+
$this->assertSame('http://example.com/foo', implode('', $response->getRequestOptions()['base_uri']));
96+
$this->assertSame('http://example.com/bar', $response->getInfo('url'));
97+
98+
$response = $client->request('GET', 'http://foo.bar/');
99+
$this->assertNull($response->getRequestOptions()['base_uri']);
100+
}
96101
}

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.