Skip to content

[HttpClient] Add UriTemplateHttpClient #49302

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1655,6 +1655,11 @@ private function addHttpClientSection(ArrayNodeDefinition $rootNode, callable $e
->normalizeKeys(false)
->variablePrototype()->end()
->end()
->arrayNode('vars')
->info('Associative array: the default vars used to expand the templated URI.')
->normalizeKeys(false)
->variablePrototype()->end()
->end()
->integerNode('max_redirects')
->info('The maximum number of redirects to follow.')
->end()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@
use Symfony\Component\HttpClient\Retry\GenericRetryStrategy;
use Symfony\Component\HttpClient\RetryableHttpClient;
use Symfony\Component\HttpClient\ScopingHttpClient;
use Symfony\Component\HttpClient\UriTemplateHttpClient;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Component\HttpKernel\CacheClearer\CacheClearerInterface;
Expand Down Expand Up @@ -2338,6 +2339,8 @@ private function registerHttpClientConfiguration(array $config, ContainerBuilder
$options = $config['default_options'] ?? [];
$retryOptions = $options['retry_failed'] ?? ['enabled' => false];
unset($options['retry_failed']);
$defaultUriTemplateVars = $options['vars'] ?? [];
unset($options['vars']);
$container->getDefinition('http_client')->setArguments([$options, $config['max_host_connections'] ?? 6]);

if (!$hasPsr18 = ContainerBuilder::willBeAvailable('psr/http-client', ClientInterface::class, ['symfony/framework-bundle', 'symfony/http-client'])) {
Expand All @@ -2349,11 +2352,31 @@ private function registerHttpClientConfiguration(array $config, ContainerBuilder
$container->removeDefinition(HttpClient::class);
}

if ($this->readConfigEnabled('http_client.retry_failed', $container, $retryOptions)) {
if ($hasRetryFailed = $this->readConfigEnabled('http_client.retry_failed', $container, $retryOptions)) {
$this->registerRetryableHttpClient($retryOptions, 'http_client', $container);
}

$httpClientId = ($retryOptions['enabled'] ?? false) ? 'http_client.retryable.inner' : ($this->isInitializedConfigEnabled('profiler') ? '.debug.http_client.inner' : 'http_client');
if ($hasUriTemplate = class_exists(UriTemplateHttpClient::class)) {
if (ContainerBuilder::willBeAvailable('guzzlehttp/uri-template', \GuzzleHttp\UriTemplate\UriTemplate::class, [])) {
$container->setAlias('http_client.uri_template_expander', 'http_client.uri_template_expander.guzzle');
} elseif (ContainerBuilder::willBeAvailable('rize/uri-template', \Rize\UriTemplate::class, [])) {
$container->setAlias('http_client.uri_template_expander', 'http_client.uri_template_expander.rize');
}

$container
->getDefinition('http_client.uri_template')
->setArgument(2, $defaultUriTemplateVars);
} elseif ($defaultUriTemplateVars) {
throw new LogicException('Support for URI template requires symfony/http-client 6.3 or higher, try upgrading.');
}

$httpClientId = match (true) {
$hasUriTemplate => 'http_client.uri_template.inner',
$hasRetryFailed => 'http_client.retryable.inner',
$this->isInitializedConfigEnabled('profiler') => '.debug.http_client.inner',
default => 'http_client',
};

foreach ($config['scoped_clients'] as $name => $scopeConfig) {
if ('http_client' === $name) {
throw new InvalidArgumentException(sprintf('Invalid scope name: "%s" is reserved.', $name));
Expand Down Expand Up @@ -2384,6 +2407,17 @@ private function registerHttpClientConfiguration(array $config, ContainerBuilder
$this->registerRetryableHttpClient($retryOptions, $name, $container);
}

if ($hasUriTemplate) {
$container
->register($name.'.uri_template', UriTemplateHttpClient::class)
->setDecoratedService($name, null, 7) // Between TraceableHttpClient (5) and RetryableHttpClient (10)
->setArguments([
new Reference('.inner'),
new Reference('http_client.uri_template_expander', ContainerInterface::NULL_ON_INVALID_REFERENCE),
$defaultUriTemplateVars,
]);
}

$container->registerAliasForArgument($name, HttpClientInterface::class);

if ($hasPsr18) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use Symfony\Component\HttpClient\HttplugClient;
use Symfony\Component\HttpClient\Psr18Client;
use Symfony\Component\HttpClient\Retry\GenericRetryStrategy;
use Symfony\Component\HttpClient\UriTemplateHttpClient;
use Symfony\Contracts\HttpClient\HttpClientInterface;

return static function (ContainerConfigurator $container) {
Expand Down Expand Up @@ -60,5 +61,25 @@
abstract_arg('max delay ms'),
abstract_arg('jitter'),
])

->set('http_client.uri_template', UriTemplateHttpClient::class)
->decorate('http_client', null, 7) // Between TraceableHttpClient (5) and RetryableHttpClient (10)
->args([
service('.inner'),
service('http_client.uri_template_expander')->nullOnInvalid(),
abstract_arg('default vars'),
])

->set('http_client.uri_template_expander.guzzle', \Closure::class)
->factory([\Closure::class, 'fromCallable'])
->args([
[\GuzzleHttp\UriTemplate\UriTemplate::class, 'expand'],
])

->set('http_client.uri_template_expander.rize', \Closure::class)
->factory([\Closure::class, 'fromCallable'])
->args([
[inline_service(\Rize\UriTemplate::class), 'expand'],
])
;
};
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\RetryableHttpClient;
use Symfony\Component\HttpClient\ScopingHttpClient;
use Symfony\Component\HttpClient\UriTemplateHttpClient;
use Symfony\Component\HttpKernel\DependencyInjection\LoggerPass;
use Symfony\Component\HttpKernel\Fragment\FragmentUriGeneratorInterface;
use Symfony\Component\Messenger\Transport\TransportFactory;
Expand Down Expand Up @@ -2003,15 +2004,15 @@ public function testHttpClientMockResponseFactory()
{
$container = $this->createContainerFromFile('http_client_mock_response_factory');

$definition = $container->getDefinition('http_client.mock_client');
$definition = $container->getDefinition(($uriTemplateHttpClientExists = class_exists(UriTemplateHttpClient::class)) ? 'http_client.uri_template.inner.mock_client' : 'http_client.mock_client');

$this->assertSame(MockHttpClient::class, $definition->getClass());
$this->assertCount(1, $definition->getArguments());

$argument = $definition->getArgument(0);

$this->assertInstanceOf(Reference::class, $argument);
$this->assertSame('http_client', current($definition->getDecoratedService()));
$this->assertSame($uriTemplateHttpClientExists ? 'http_client.uri_template.inner' : 'http_client', current($definition->getDecoratedService()));
$this->assertSame('my_response_factory', (string) $argument);
}

Expand Down
5 changes: 5 additions & 0 deletions src/Symfony/Component/HttpClient/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

6.3
---

* Add `UriTemplateHttpClient` to use URI templates as specified in the RFC 6570

6.2
---

Expand Down
4 changes: 4 additions & 0 deletions src/Symfony/Component/HttpClient/HttpClientTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,10 @@ private static function mergeDefaultOptions(array $options, array $defaultOption
throw new InvalidArgumentException(sprintf('Option "auth_ntlm" is not supported by "%s", '.$msg, __CLASS__, CurlHttpClient::class));
}

if ('vars' === $name) {
throw new InvalidArgumentException(sprintf('Option "vars" is not supported by "%s", try using "%s" instead.', __CLASS__, UriTemplateHttpClient::class));
}

$alternatives = [];

foreach ($defaultOptions as $k => $v) {
Expand Down
10 changes: 10 additions & 0 deletions src/Symfony/Component/HttpClient/HttpOptions.php
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,16 @@ public function setBaseUri(string $uri): static
return $this;
}

/**
* @return $this
*/
public function setVars(array $vars): static
{
$this->options['vars'] = $vars;

return $this;
}

/**
* @return $this
*/
Expand Down
129 changes: 129 additions & 0 deletions src/Symfony/Component/HttpClient/Tests/UriTemplateHttpClientTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\HttpClient\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\MockResponse;
use Symfony\Component\HttpClient\UriTemplateHttpClient;

final class UriTemplateHttpClientTest extends TestCase
{
public function testExpanderIsCalled()
{
$client = new UriTemplateHttpClient(
new MockHttpClient(),
function (string $url, array $vars): string {
$this->assertSame('https://foo.tld/{version}/{resource}{?page}', $url);
$this->assertSame([
'version' => 'v2',
'resource' => 'users',
'page' => 33,
], $vars);

return 'https://foo.tld/v2/users?page=33';
},
[
'version' => 'v2',
],
);
$this->assertSame('https://foo.tld/v2/users?page=33', $client->request('GET', 'https://foo.tld/{version}/{resource}{?page}', [
'vars' => [
'resource' => 'users',
'page' => 33,
],
])->getInfo('url'));
}

public function testWithOptionsAppendsVarsToDefaultVars()
{
$client = new UriTemplateHttpClient(
new MockHttpClient(),
function (string $url, array $vars): string {
$this->assertSame('https://foo.tld/{bar}', $url);
$this->assertSame([
'bar' => 'ccc',
], $vars);

return 'https://foo.tld/ccc';
},
);
$this->assertSame('https://foo.tld/{bar}', $client->request('GET', 'https://foo.tld/{bar}')->getInfo('url'));

$client = $client->withOptions([
'vars' => [
'bar' => 'ccc',
],
]);
$this->assertSame('https://foo.tld/ccc', $client->request('GET', 'https://foo.tld/{bar}')->getInfo('url'));
}

public function testExpanderIsNotCalledWithEmptyVars()
{
$this->expectNotToPerformAssertions();

$client = new UriTemplateHttpClient(new MockHttpClient(), $this->fail(...));
$client->request('GET', 'https://foo.tld/bar', [
'vars' => [],
]);
}

public function testExpanderIsNotCalledWithNoVarsAtAll()
{
$this->expectNotToPerformAssertions();

$client = new UriTemplateHttpClient(new MockHttpClient(), $this->fail(...));
$client->request('GET', 'https://foo.tld/bar');
}

public function testRequestWithNonArrayVarsOption()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('The "vars" option must be an array.');

(new UriTemplateHttpClient(new MockHttpClient()))->request('GET', 'https://foo.tld', [
'vars' => 'should be an array',
]);
}

public function testWithOptionsWithNonArrayVarsOption()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('The "vars" option must be an array.');

(new UriTemplateHttpClient(new MockHttpClient()))->withOptions([
'vars' => new \stdClass(),
]);
}

public function testVarsOptionIsNotPropagated()
{
$client = new UriTemplateHttpClient(
new MockHttpClient(function (string $method, string $url, array $options): MockResponse {
$this->assertArrayNotHasKey('vars', $options);

return new MockResponse();
}),
static fn (): string => 'ccc',
);

$client->withOptions([
'vars' => [
'foo' => 'bar',
],
])->request('GET', 'https://foo.tld', [
'vars' => [
'foo2' => 'bar2',
],
]);
}
}
84 changes: 84 additions & 0 deletions src/Symfony/Component/HttpClient/UriTemplateHttpClient.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\HttpClient;

use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
use Symfony\Contracts\Service\ResetInterface;

class UriTemplateHttpClient implements HttpClientInterface, ResetInterface
{
use DecoratorTrait;

/**
* @param (\Closure(string $url, array $vars): string)|null $expander
*/
public function __construct(HttpClientInterface $client = null, private ?\Closure $expander = null, private array $defaultVars = [])
{
$this->client = $client ?? HttpClient::create();
}

public function request(string $method, string $url, array $options = []): ResponseInterface
{
$vars = $this->defaultVars;

if (\array_key_exists('vars', $options)) {
if (!\is_array($options['vars'])) {
throw new \InvalidArgumentException('The "vars" option must be an array.');
}

$vars = [...$vars, ...$options['vars']];
unset($options['vars']);
}

if ($vars) {
$url = ($this->expander ??= $this->createExpanderFromPopularVendors())($url, $vars);
}

return $this->client->request($method, $url, $options);
}

public function withOptions(array $options): static
{
if (!\is_array($options['vars'] ?? [])) {
throw new \InvalidArgumentException('The "vars" option must be an array.');
}

$clone = clone $this;
$clone->defaultVars = [...$clone->defaultVars, ...$options['vars'] ?? []];
unset($options['vars']);

$clone->client = $this->client->withOptions($options);

return $clone;
}

/**
* @return \Closure(string $url, array $vars): string
*/
private function createExpanderFromPopularVendors(): \Closure
{
if (class_exists(\GuzzleHttp\UriTemplate\UriTemplate::class)) {
return \GuzzleHttp\UriTemplate\UriTemplate::expand(...);
}

if (class_exists(\League\Uri\UriTemplate::class)) {
return static fn (string $url, array $vars): string => (new \League\Uri\UriTemplate($url))->expand($vars);
}

if (class_exists(\Rize\UriTemplate::class)) {
return (new \Rize\UriTemplate())->expand(...);
}

throw new \LogicException('Support for URI template requires a vendor to expand the URI. Run "composer require guzzlehttp/uri-template" or pass your own expander \Closure implementation.');
}
}