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

QueryDefaultsPlugin   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 2
dl 0
loc 39
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 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