Completed
Pull Request — master (#67)
by Tobias
03:08 queued 01:11
created

QueryDefaultsPlugin::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 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
24
     */
25 3
    public function __construct(array $queryParams)
26
    {
27 3
        $this->queryParams = $queryParams;
28 3
    }
29
30
    /**
31
     * {@inheritdoc}
32
     */
33 1
    public function handleRequest(RequestInterface $request, callable $next, callable $first)
34
    {
35 1
        foreach ($this->queryParams as $name => $value) {
36 1
            $uri = $request->getUri();
37 1
            $array = [];
38 1
            parse_str($uri->getQuery(), $array);
39
40
            // If query value is not found
41 1
            if (!isset($array[$name])) {
42 1
                $array[$name] = $value;
43
44
                // Create a new request with the new URI with the added query param
45 1
                $request = $request->withUri(
46 1
                    $uri->withQuery(http_build_query($array))
47 1
                );
48 1
            }
49 1
        }
50
51 1
        return $next($request);
52
    }
53
}
54