Completed
Pull Request — master (#67)
by Tobias
09:43
created

QueryDefaultsPlugin::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Http\Client\Common\Plugin;
4
5
use Http\Client\Common\Plugin;
6
use Psr\Http\Message\RequestInterface;
7
8
/**
9
 * Set query to default value if it does not exist.
10
 *
11
 * If a given query parameter already exists the value wont be replaced and the request wont be changed.
12
 *
13
 * @author Tobias Nyholm <[email protected]>
14
 */
15
final class QueryDefaultsPlugin implements Plugin
16
{
17
    /**
18
     * @var array
19
     */
20
    private $queryParams = [];
21
22
    /**
23
     * @param array $queryParams Hashmap of query name to query value. Names and values should not be url encoded.
24
     */
25
    public function __construct(array $queryParams)
26
    {
27
        $this->queryParams = $queryParams;
28
    }
29
30
    /**
31
     * {@inheritdoc}
32
     */
33
    public function handleRequest(RequestInterface $request, callable $next, callable $first)
34
    {
35
        foreach ($this->queryParams as $name => $value) {
36
            $uri = $request->getUri();
37
            $array = [];
38
            parse_str($uri->getQuery(), $array);
39
40
            // If query value is not found
41
            if (!isset($array[$name])) {
42
                $array[$name] = $value;
43
44
                // Create a new request with the new URI with the added query param
45
                $request = $request->withUri(
46
                    $uri->withQuery(http_build_query($array))
47
                );
48
            }
49
        }
50
51
        return $next($request);
52
    }
53
}
54