From e47ccf677b0c0a7b993047285c7424934246a46b Mon Sep 17 00:00:00 2001 From: Simon Podlipsky Date: Thu, 18 Jul 2024 12:12:44 +0200 Subject: [PATCH] Add support for keeping boolean values "as is" in query (#603) * 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 --- src/Query.php | 18 +++++++++++------- tests/QueryTest.php | 6 ++++++ 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/src/Query.php b/src/Query.php index 8b949279..daddf998 100644 --- a/src/Query.php +++ b/src/Query.php @@ -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 ''; @@ -86,12 +88,14 @@ 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); } @@ -99,7 +103,7 @@ public static function build(array $params, $encoding = PHP_QUERY_RFC3986): stri } 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); } diff --git a/tests/QueryTest.php b/tests/QueryTest.php index d9ebadf7..af396378 100644 --- a/tests/QueryTest.php +++ b/tests/QueryTest.php @@ -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)); } }