diff --git a/spec/Plugin/QueryDefaultsPluginSpec.php b/spec/Plugin/QueryDefaultsPluginSpec.php index e4c88d0..82d9125 100644 --- a/spec/Plugin/QueryDefaultsPluginSpec.php +++ b/spec/Plugin/QueryDefaultsPluginSpec.php @@ -39,4 +39,21 @@ public function it_sets_the_default_header(RequestInterface $request, UriInterfa }, function () { }); } + + public function it_does_not_replace_existing_request_value(RequestInterface $request, UriInterface $uri) + { + $this->beConstructedWith([ + 'foo' => 'fooDefault', + 'bar' => 'barDefault', + ]); + + $request->getUri()->shouldBeCalled()->willReturn($uri); + $uri->getQuery()->shouldBeCalled()->willReturn('foo=new'); + $uri->withQuery('foo=new&bar=barDefault')->shouldBeCalled()->willReturn($uri); + $request->withUri($uri)->shouldBeCalled()->willReturn($request); + + $this->handleRequest($request, function () { + }, function () { + }); + } } diff --git a/src/Plugin/QueryDefaultsPlugin.php b/src/Plugin/QueryDefaultsPlugin.php index 6c1e32c..d9c06d6 100644 --- a/src/Plugin/QueryDefaultsPlugin.php +++ b/src/Plugin/QueryDefaultsPlugin.php @@ -33,21 +33,14 @@ public function __construct(array $queryParams) */ public function handleRequest(RequestInterface $request, callable $next, callable $first) { - foreach ($this->queryParams as $name => $value) { - $uri = $request->getUri(); - $array = []; - parse_str($uri->getQuery(), $array); - - // If query value is not found - if (!isset($array[$name])) { - $array[$name] = $value; - - // Create a new request with the new URI with the added query param - $request = $request->withUri( - $uri->withQuery(http_build_query($array)) - ); - } - } + $uri = $request->getUri(); + + parse_str($uri->getQuery(), $query); + $query += $this->queryParams; + + $request = $request->withUri( + $uri->withQuery(http_build_query($query)) + ); return $next($request); }