1: <?php
2:
3: declare(strict_types=1);
4:
5: namespace OpenSearch\HttpClient;
6:
7: use GuzzleHttp\Client as GuzzleClient;
8: use GuzzleHttp\HandlerStack;
9: use GuzzleHttp\Middleware;
10: use OpenSearch\Client;
11: use Psr\Log\LoggerInterface;
12:
13: /**
14: * Builds an OpenSearch client using Guzzle.
15: */
16: class GuzzleHttpClientFactory implements HttpClientFactoryInterface
17: {
18: public function __construct(
19: protected int $maxRetries = 0,
20: protected ?LoggerInterface $logger = null,
21: ) {
22: }
23:
24: /**
25: * {@inheritdoc}
26: */
27: public function create(array $options): GuzzleClient
28: {
29: if (!isset($options['base_uri'])) {
30: throw new \InvalidArgumentException('The base_uri option is required.');
31: }
32: // Set default configuration.
33: $defaults = [
34: 'headers' => [
35: 'Accept' => 'application/json',
36: 'Content-Type' => 'application/json',
37: 'User-Agent' => sprintf('opensearch-php/%s (%s; PHP %s)', Client::VERSION, PHP_OS, PHP_VERSION),
38: ],
39: ];
40:
41: // Merge the default options with the provided options.
42: $config = array_merge_recursive($defaults, $options);
43:
44: $stack = HandlerStack::create();
45:
46: // Handle retries if max_retries is set.
47: if ($this->maxRetries > 0) {
48: $decider = new GuzzleRetryDecider($this->maxRetries, $this->logger);
49: $stack->push(Middleware::retry($decider(...)));
50: }
51:
52: $config['handler'] = $stack;
53:
54: return new GuzzleClient($config);
55: }
56:
57: }
58: