-
-
Notifications
You must be signed in to change notification settings - Fork 49
/
UriTemplateHttpClient.php
84 lines (66 loc) · 2.68 KB
/
UriTemplateHttpClient.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* 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.');
}
}