| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
namespace Symfony\Component\HttpClient; |
| 13 |
|
| 14 |
use Symfony\Contracts\HttpClient\HttpClientInterface; |
| 15 |
use Symfony\Contracts\HttpClient\ResponseInterface; |
| 16 |
use Symfony\Contracts\Service\ResetInterface; |
| 17 |
|
| 18 |
class UriTemplateHttpClient implements HttpClientInterface, ResetInterface |
| 19 |
{ |
| 20 |
use DecoratorTrait; |
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
public function __construct(?HttpClientInterface $client = null, private ?\Closure $expander = null, private array $defaultVars = []) |
| 26 |
{ |
| 27 |
$this->client = $client ?? HttpClient::create(); |
| 28 |
} |
| 29 |
|
| 30 |
public function request(string $method, string $url, array $options = []): ResponseInterface |
| 31 |
{ |
| 32 |
$vars = $this->defaultVars; |
| 33 |
|
| 34 |
if (\array_key_exists('vars', $options)) { |
| 35 |
if (!\is_array($options['vars'])) { |
| 36 |
throw new \InvalidArgumentException('The "vars" option must be an array.'); |
| 37 |
} |
| 38 |
|
| 39 |
$vars = [...$vars, ...$options['vars']]; |
| 40 |
unset($options['vars']); |
| 41 |
} |
| 42 |
|
| 43 |
if ($vars) { |
| 44 |
$url = ($this->expander ??= $this->createExpanderFromPopularVendors())($url, $vars); |
| 45 |
} |
| 46 |
|
| 47 |
return $this->client->request($method, $url, $options); |
| 48 |
} |
| 49 |
|
| 50 |
public function withOptions(array $options): static |
| 51 |
{ |
| 52 |
if (!\is_array($options['vars'] ?? [])) { |
| 53 |
throw new \InvalidArgumentException('The "vars" option must be an array.'); |
| 54 |
} |
| 55 |
|
| 56 |
$clone = clone $this; |
| 57 |
$clone->defaultVars = [...$clone->defaultVars, ...$options['vars'] ?? []]; |
| 58 |
unset($options['vars']); |
| 59 |
|
| 60 |
$clone->client = $this->client->withOptions($options); |
| 61 |
|
| 62 |
return $clone; |
| 63 |
} |
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
private function createExpanderFromPopularVendors(): \Closure |
| 69 |
{ |
| 70 |
if (class_exists(\GuzzleHttp\UriTemplate\UriTemplate::class)) { |
| 71 |
return \GuzzleHttp\UriTemplate\UriTemplate::expand(...); |
| 72 |
} |
| 73 |
|
| 74 |
if (class_exists(\League\Uri\UriTemplate::class)) { |
| 75 |
return static fn (string $url, array $vars): string => (new \League\Uri\UriTemplate($url))->expand($vars); |
| 76 |
} |
| 77 |
|
| 78 |
if (class_exists(\Rize\UriTemplate::class)) { |
| 79 |
return (new \Rize\UriTemplate())->expand(...); |
| 80 |
} |
| 81 |
|
| 82 |
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.'); |
| 83 |
} |
| 84 |
} |