1: | <?php |
2: | |
3: | namespace OpenSearch; |
4: | |
5: | use OpenSearch\Serializers\SerializerInterface; |
6: | use Psr\Http\Message\RequestFactoryInterface as PsrRequestFactoryInterface; |
7: | use Psr\Http\Message\RequestInterface; |
8: | use Psr\Http\Message\StreamFactoryInterface; |
9: | use Psr\Http\Message\UriFactoryInterface; |
10: | |
11: | |
12: | |
13: | |
14: | final class RequestFactory implements RequestFactoryInterface |
15: | { |
16: | public function __construct( |
17: | protected PsrRequestFactoryInterface $psrRequestFactory, |
18: | protected StreamFactoryInterface $streamFactory, |
19: | protected UriFactoryInterface $uriFactory, |
20: | protected SerializerInterface $serializer, |
21: | ) { |
22: | } |
23: | |
24: | |
25: | |
26: | |
27: | public function createRequest( |
28: | string $method, |
29: | string $uri, |
30: | array $params = [], |
31: | string|array|null $body = null, |
32: | array $headers = [], |
33: | ): RequestInterface { |
34: | $uri = $this->uriFactory->createUri($uri); |
35: | $uri = $uri->withQuery($this->createQuery($params)); |
36: | $request = $this->psrRequestFactory->createRequest($method, $uri); |
37: | if ($body !== null) { |
38: | $bodyJson = $this->serializer->serialize($body); |
39: | $bodyStream = $this->streamFactory->createStream($bodyJson); |
40: | $request = $request->withBody($bodyStream); |
41: | } |
42: | foreach ($headers as $name => $value) { |
43: | $request = $request->withHeader($name, $value); |
44: | } |
45: | return $request; |
46: | } |
47: | |
48: | |
49: | |
50: | |
51: | private function createQuery(array $params): string |
52: | { |
53: | return http_build_query(array_map(function ($value) { |
54: | |
55: | if ($value === true) { |
56: | return 'true'; |
57: | } |
58: | if ($value === false) { |
59: | return 'false'; |
60: | } |
61: | return $value; |
62: | }, $params)); |
63: | } |
64: | |
65: | } |
66: | |