Skip to content

Commit 7533c2d

Browse files
authored
Merge pull request #94 from vudaltsov/improve-query-defaults
Improved performance of QueryDefaultsPlugin
2 parents 9accb4a + b3148f8 commit 7533c2d

File tree

2 files changed

+25
-15
lines changed

2 files changed

+25
-15
lines changed

spec/Plugin/QueryDefaultsPluginSpec.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,4 +39,21 @@ public function it_sets_the_default_header(RequestInterface $request, UriInterfa
3939
}, function () {
4040
});
4141
}
42+
43+
public function it_does_not_replace_existing_request_value(RequestInterface $request, UriInterface $uri)
44+
{
45+
$this->beConstructedWith([
46+
'foo' => 'fooDefault',
47+
'bar' => 'barDefault',
48+
]);
49+
50+
$request->getUri()->shouldBeCalled()->willReturn($uri);
51+
$uri->getQuery()->shouldBeCalled()->willReturn('foo=new');
52+
$uri->withQuery('foo=new&bar=barDefault')->shouldBeCalled()->willReturn($uri);
53+
$request->withUri($uri)->shouldBeCalled()->willReturn($request);
54+
55+
$this->handleRequest($request, function () {
56+
}, function () {
57+
});
58+
}
4259
}

src/Plugin/QueryDefaultsPlugin.php

Lines changed: 8 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -33,21 +33,14 @@ public function __construct(array $queryParams)
3333
*/
3434
public function handleRequest(RequestInterface $request, callable $next, callable $first)
3535
{
36-
foreach ($this->queryParams as $name => $value) {
37-
$uri = $request->getUri();
38-
$array = [];
39-
parse_str($uri->getQuery(), $array);
40-
41-
// If query value is not found
42-
if (!isset($array[$name])) {
43-
$array[$name] = $value;
44-
45-
// Create a new request with the new URI with the added query param
46-
$request = $request->withUri(
47-
$uri->withQuery(http_build_query($array))
48-
);
49-
}
50-
}
36+
$uri = $request->getUri();
37+
38+
parse_str($uri->getQuery(), $query);
39+
$query += $this->queryParams;
40+
41+
$request = $request->withUri(
42+
$uri->withQuery(http_build_query($query))
43+
);
5144

5245
return $next($request);
5346
}

0 commit comments

Comments
 (0)