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: | |
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: | |
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: | |
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: | |
41: | |
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: | |
53: | |
54: | if ($statusCode >= 400) { |
55: | |
56: | throw HttpExceptionFactory::create($statusCode, $data); |
57: | } |
58: | return $data; |
59: | } |
60: | |
61: | } |
62: | |