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: | |
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: | |
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: | |
33: | $middlewares = []; |
34: | if (isset($options['middleware'])) { |
35: | $middlewares = $options['middleware']; |
36: | unset($options['middleware']); |
37: | if (!is_array($middlewares)) { |
38: | $middlewares = [$middlewares]; |
39: | } |
40: | } |
41: | |
42: | |
43: | $defaults = [ |
44: | 'headers' => [ |
45: | 'Accept' => 'application/json', |
46: | 'Content-Type' => 'application/json', |
47: | 'User-Agent' => sprintf('opensearch-php/%s (%s; PHP %s)', Client::VERSION, PHP_OS, PHP_VERSION), |
48: | ], |
49: | ]; |
50: | |
51: | |
52: | $config = array_merge_recursive($defaults, $options); |
53: | |
54: | $stack = HandlerStack::create(); |
55: | |
56: | |
57: | if ($this->maxRetries > 0) { |
58: | $decider = new GuzzleRetryDecider($this->maxRetries, $this->logger); |
59: | $stack->push(Middleware::retry($decider(...))); |
60: | } |
61: | |
62: | |
63: | foreach ($middlewares as $name => $middleware) { |
64: | if (is_callable($middleware)) { |
65: | |
66: | if (is_int($name) || is_numeric($name)) { |
67: | $name = ''; |
68: | } |
69: | $stack->push($middleware, $name); |
70: | } |
71: | } |
72: | |
73: | $config['handler'] = $stack; |
74: | |
75: | return new GuzzleClient($config); |
76: | } |
77: | |
78: | } |
79: | |