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

QueryDefaultsPlugin   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 2
dl 0
loc 40
ccs 16
cts 16
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A handleRequest() 0 20 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