1: <?php
2:
3: namespace OpenSearch;
4:
5: use OpenSearch\Exception\HttpExceptionFactory;
6: use OpenSearch\Serializers\SerializerInterface;
7: use Psr\Http\Client\ClientInterface;
8: use Psr\Http\Message\RequestInterface;
9:
10: /**
11: * Transport that uses PSR-7, PSR-17 and PSR-18 interfaces.
12: */
13: final class HttpTransport implements TransportInterface
14: {
15: public function __construct(
16: protected ClientInterface $client,
17: protected RequestFactoryInterface $requestFactory,
18: protected SerializerInterface $serializer,
19: ) {
20: }
21:
22: /**
23: * Create a new request.
24: */
25: public function createRequest(string $method, string $uri, array $params = [], mixed $body = null, array $headers = []): RequestInterface
26: {
27: return $this->requestFactory->createRequest($method, $uri, $params, $body, $headers);
28: }
29:
30: /**
31: * {@inheritdoc}
32: */
33: public function sendRequest(
34: string $method,
35: string $uri,
36: array $params = [],
37: mixed $body = null,
38: array $headers = [],
39: ): iterable|string|null {
40: // @todo Remove support for legacy options in 3.0.0.
41: // @phpstan-ignore isset.offset
42: if (isset($headers['client']['headers'])) {
43: $headers = array_merge($headers, $headers['client']['headers']);
44: }
45: unset($headers['client']);
46: $request = $this->createRequest($method, $uri, $params, $body, $headers);
47: $response = $this->client->sendRequest($request);
48: $statusCode = $response->getStatusCode();
49: $responseBody = $response->getBody()->getContents();
50: $responseHeaders = $response->getHeaders();
51: $data = $this->serializer->deserialize($responseBody, $responseHeaders);
52: // Status code >= 200 < 300 is a success.
53: // Status code >= 300 < 400 is a redirect and should be handled by the client.
54: if ($statusCode >= 400) {
55: // Throw an HTTP exception.
56: throw HttpExceptionFactory::create($statusCode, $data);
57: }
58: return $data;
59: }
60:
61: }
62: