diff --git a/src/QueryParameterBag.php b/src/QueryParameterBag.php index 4e4c205..68b699e 100644 --- a/src/QueryParameterBag.php +++ b/src/QueryParameterBag.php @@ -65,6 +65,10 @@ class QueryParameterBag implements \Stringable public function __toString(): string { - return http_build_query($this->parameters, '', '&', PHP_QUERY_RFC3986); + // Valueless parameters are stored as null, which http_build_query() skips; + // render them with an empty value so they survive. + $parameters = array_map(fn ($value) => $value ?? '', $this->parameters); + + return http_build_query($parameters, '', '&', PHP_QUERY_RFC3986); } } diff --git a/tests/QueryParameterBagTest.php b/tests/QueryParameterBagTest.php index 55f870c..bfc8fe1 100644 --- a/tests/QueryParameterBagTest.php +++ b/tests/QueryParameterBagTest.php @@ -89,6 +89,21 @@ it('can be casted to a string', function () { }); +it('keeps valueless parameters when being casted to a string', function () { + $queryParameterBag = QueryParameterBag::fromString('offset'); + + expect($queryParameterBag)->has('offset')->toBeTrue(); + expect($queryParameterBag)->__toString()->toEqual('offset='); +}); + + +it('keeps valueless parameters alongside valued ones when being casted to a string', function () { + $queryParameterBag = QueryParameterBag::fromString('foo=&bar=baz'); + + expect($queryParameterBag)->__toString()->toEqual('foo=&bar=baz'); +}); + + it('can be created from a string with url encoded values', function () { $queryParameterBag = QueryParameterBag::fromString( 'category=storage%20furniture&discount=%3E40%25%20off&range%5B0%5D=10&range%5B1%5D=20'