Completed
Pull Request — master (#44)
by
unknown
02:52
created

HeaderPlugin   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
c 1
b 0
f 0
lcom 1
cbo 1
dl 0
loc 51
ccs 18
cts 18
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A withHeader() 0 4 1
A withoutHeader() 0 4 1
B handleRequest() 0 15 6
1
<?php
2
3
namespace Http\Client\Plugin;
4
5
use Psr\Http\Message\RequestInterface;
6
7
/**
8
 * Manages http headers.
9
 */
10
class HeaderPlugin implements Plugin
11
{
12
13
    /**
14
     * @var array headers that have fixed value
15
     */
16
    private $headers = [];
17
    private $removedHeader = [];
18
19
    /**
20
     * Sets a header with the given value to every requests.
21
     *
22
     * @param string $name      name of the header
23
     * @param string $value     value of the header
24
     * @param bool $override    By default if the header is already set on the request the value wont be replaced
25
     * pass $override to true to make the header value the same for every request
26
     */
27 3
    public function withHeader($name, $value, $override = false)
28
    {
29 3
        $this->headers[$name] = ['value' => $value, 'override' => $override];
30 3
    }
31
32
    /**
33
     * Automatically removes the given header from the request.
34
     *
35
     * @param string $name name of the header to remove
36
     */
37 2
    public function withoutHeader($name)
38
    {
39 2
        $this->removedHeader[] = $name;
40 2
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45 5
    public function handleRequest(RequestInterface $request, callable $next, callable $first)
46
    {
47 5
        foreach ($this->headers as $header => $headerData) {
48 3
            if ($headerData['override'] || !$request->hasHeader($header)) {
49 2
                $request = $request->withHeader($header, $headerData['value']);
50 2
            }
51 5
        }
52 5
        foreach ($this->removedHeader as $header) {
53 2
            if ($request->hasHeader($header)) {
54 1
                $request = $request->withoutHeader($header);
55 1
            }
56 5
        }
57
58 5
        return $next($request);
59
    }
60
}
61