Completed
Push — master ( 85b250...c53e99 )
by Tobias
03:01
created

QueryDefaultsPlugin::handleRequest()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 3

Importance

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