Skip to content

Commit

Permalink
Serialize boolean query string params as strings
Browse files Browse the repository at this point in the history
Signed-off-by: Kim Pepper <[email protected]>
  • Loading branch information
kimpepper committed Feb 3, 2025
1 parent 92b8e45 commit a59af21
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
21 changes: 20 additions & 1 deletion src/OpenSearch/RequestFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public function createRequest(
array $headers = [],
): RequestInterface {
$uri = $this->uriFactory->createUri($uri);
$uri = $uri->withQuery(http_build_query($params));
$uri = $uri->withQuery($this->createQuery($params));
$request = $this->psrRequestFactory->createRequest($method, $uri);
if ($body !== null) {
$bodyJson = $this->serializer->serialize($body);
Expand All @@ -45,4 +45,23 @@ public function createRequest(
return $request;
}

/**
* Create a query string from an array of parameters.
*/
private function createQuery(array $params): string
{
ksort($params);

return http_build_query(array_map(function ($value) {
// Ensure boolean values are serialized as strings.
if ($value === true) {
return 'true';
}
if ($value === false) {
return 'false';
}
return $value;
}, $params));
}

}
31 changes: 31 additions & 0 deletions tests/RequestFactoryTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

declare(strict_types=1);

namespace OpenSearch\Tests;

use GuzzleHttp\Psr7\HttpFactory;
use OpenSearch\RequestFactory;
use OpenSearch\Serializers\SerializerInterface;
use PHPUnit\Framework\TestCase;

/**
* Tests the request factory.
*
* @coversDefaultClass \OpenSearch\RequestFactory
*/
class RequestFactoryTest extends TestCase
{
public function testBoolean(): void
{
$httpFactory = new HttpFactory();
$serializer = $this->createMock(SerializerInterface::class);

$factory = new RequestFactory($httpFactory, $httpFactory, $httpFactory, $serializer);

$params = ['foo' => true, 'bar' => false];
$request = $factory->createRequest('GET', 'http://localhost:9200/_search', $params);

$this->assertEquals('bar=false&foo=true', $request->getUri()->getQuery());
}
}

0 comments on commit a59af21

Please sign in to comment.