diff --git a/CHANGELOG.md b/CHANGELOG.md index 6df8e3e..b0ca21a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Change Log +## Unreleased + +### Added + +- `QueryDefaultsPlugin` to add default query parameters. ## 1.4.2 - 2017-03-18 diff --git a/spec/Plugin/QueryDefaultsPluginSpec.php b/spec/Plugin/QueryDefaultsPluginSpec.php new file mode 100644 index 0000000..e4c88d0 --- /dev/null +++ b/spec/Plugin/QueryDefaultsPluginSpec.php @@ -0,0 +1,42 @@ +beConstructedWith([]); + } + + public function it_is_initializable() + { + $this->shouldHaveType('Http\Client\Common\Plugin\QueryDefaultsPlugin'); + } + + public function it_is_a_plugin() + { + $this->shouldImplement('Http\Client\Common\Plugin'); + } + + public function it_sets_the_default_header(RequestInterface $request, UriInterface $uri) + { + $this->beConstructedWith([ + 'foo' => 'bar', + ]); + + $request->getUri()->shouldBeCalled()->willReturn($uri); + $uri->getQuery()->shouldBeCalled()->willReturn('test=true'); + $uri->withQuery('test=true&foo=bar')->shouldBeCalled()->willReturn($uri); + $request->withUri($uri)->shouldBeCalled()->willReturn($request); + + $this->handleRequest($request, function () { + }, function () { + }); + } +} diff --git a/src/Plugin/HeaderAppendPlugin.php b/src/Plugin/HeaderAppendPlugin.php index 1e7b320..26fd813 100644 --- a/src/Plugin/HeaderAppendPlugin.php +++ b/src/Plugin/HeaderAppendPlugin.php @@ -12,7 +12,7 @@ * * This only makes sense for headers that can have multiple values like 'Forwarded' * - * @link https://en.wikipedia.org/wiki/List_of_HTTP_header_fields + * @see https://en.wikipedia.org/wiki/List_of_HTTP_header_fields * * @author Soufiane Ghzal */ diff --git a/src/Plugin/QueryDefaultsPlugin.php b/src/Plugin/QueryDefaultsPlugin.php new file mode 100644 index 0000000..6c1e32c --- /dev/null +++ b/src/Plugin/QueryDefaultsPlugin.php @@ -0,0 +1,54 @@ + + */ +final class QueryDefaultsPlugin implements Plugin +{ + /** + * @var array + */ + private $queryParams = []; + + /** + * @param array $queryParams Hashmap of query name to query value. Names and values must not be url encoded as + * this plugin will encode them + */ + public function __construct(array $queryParams) + { + $this->queryParams = $queryParams; + } + + /** + * {@inheritdoc} + */ + 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)) + ); + } + } + + return $next($request); + } +}