Skip to content

Commit

Permalink
Merge pull request #94 from vudaltsov/improve-query-defaults
Browse files Browse the repository at this point in the history
Improved performance of QueryDefaultsPlugin
  • Loading branch information
joelwurtz committed Apr 5, 2018
2 parents 9accb4a + b3148f8 commit 7533c2d
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 15 deletions.
17 changes: 17 additions & 0 deletions spec/Plugin/QueryDefaultsPluginSpec.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 () {
});
}
}
23 changes: 8 additions & 15 deletions src/Plugin/QueryDefaultsPlugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down

0 comments on commit 7533c2d

Please sign in to comment.