diff --git a/README.md b/README.md index 40bb01e9..2e9bb0b9 100644 --- a/README.md +++ b/README.md @@ -436,7 +436,7 @@ will be parsed into `['foo[a]' => '1', 'foo[b]' => '2'])`. ## `GuzzleHttp\Psr7\Query::build` -`public static function build(array $params, int|false $encoding = PHP_QUERY_RFC3986): string` +`public static function build(array $params, int|false $encoding = PHP_QUERY_RFC3986, bool $treatBoolsAsInts = true): string` Build a query string from an array of key value pairs. diff --git a/src/Query.php b/src/Query.php index 8b949279..3debb9b6 100644 --- a/src/Query.php +++ b/src/Query.php @@ -63,12 +63,15 @@ 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 $treatBoolsAsInts Set to true to encode as 0/1, and + * false as false/true. */ - public static function build(array $params, $encoding = PHP_QUERY_RFC3986): string + public static function build(array $params, $encoding = PHP_QUERY_RFC3986, bool $treatBoolsAsInts = true): string { if (!$params) { return ''; @@ -86,12 +89,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 +104,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)); } }