Skip to content

Commit

Permalink
Add support for keeping boolean values "as is" in query (#603)
Browse files Browse the repository at this point in the history
* feat: add support for keeping boolean values "as is" in query

* Update QueryTest.php

* Update Query.php

* Update Query.php

---------

Co-authored-by: Graham Campbell <GrahamCampbell@users.noreply.github.com>
  • Loading branch information
simPod and GrahamCampbell authored Jul 18, 2024
1 parent 6de2986 commit e47ccf6
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 7 deletions.
18 changes: 11 additions & 7 deletions src/Query.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,14 @@ public static function parse(string $str, $urlEncoding = true): array
* string. This function does not modify the provided keys when an array is
* encountered (like `http_build_query()` would).
*
* @param array $params Query string parameters.
* @param int|false $encoding Set to false to not encode, PHP_QUERY_RFC3986
* to encode using RFC3986, or PHP_QUERY_RFC1738
* to encode using RFC1738.
* @param array $params Query string parameters.
* @param int|false $encoding Set to false to not encode, PHP_QUERY_RFC3986
* to encode using RFC3986, or PHP_QUERY_RFC1738
* to encode using RFC1738.
* @param bool $treatBooleansAsInts When `true` values are cast to int (e.g. ['foo' => false] gives `foo=0`).
* When `false` values are cast to strings (e.g. ['foo' => false] gives `foo=false`).
*/
public static function build(array $params, $encoding = PHP_QUERY_RFC3986): string
public static function build(array $params, $encoding = PHP_QUERY_RFC3986, bool $treatBooleansAsInts = true): string
{
if (!$params) {
return '';
Expand All @@ -86,20 +88,22 @@ public static function build(array $params, $encoding = PHP_QUERY_RFC3986): stri
throw new \InvalidArgumentException('Invalid type');
}

$castBool = $treatBooleansAsInts ? static function ($v) { return (int) $v; } : static function ($v) { return $v ? 'true' : 'false'; };

$qs = '';
foreach ($params as $k => $v) {
$k = $encoder((string) $k);
if (!is_array($v)) {
$qs .= $k;
$v = is_bool($v) ? (int) $v : $v;
$v = is_bool($v) ? $castBool($v) : $v;
if ($v !== null) {
$qs .= '='.$encoder((string) $v);
}
$qs .= '&';
} else {
foreach ($v as $vv) {
$qs .= $k;
$vv = is_bool($vv) ? (int) $vv : $vv;
$vv = is_bool($vv) ? $castBool($vv) : $vv;
if ($vv !== null) {
$qs .= '='.$encoder((string) $vv);
}
Expand Down
6 changes: 6 additions & 0 deletions tests/QueryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -114,5 +114,11 @@ public function testBuildBooleans(): void
'bar' => [false, 'false'],
];
self::assertEquals('foo=1&foo=true&bar=0&bar=false', Psr7\Query::build($data, PHP_QUERY_RFC1738));

$data = [
'foo' => true,
'bar' => false,
];
self::assertEquals('foo=true&bar=false', Psr7\Query::build($data, PHP_QUERY_RFC3986, false));
}
}

0 comments on commit e47ccf6

Please sign in to comment.