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

HeaderPlugin::withHeader()   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 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 3
crap 1
1
<?php
2
3
namespace Http\Client\Plugin;
4
5
use Http\Message\Encoding\ChunkStream;
6
use Psr\Http\Message\RequestInterface;
7
8
/**
9
 * Manages http headers
10
 */
11
class HeaderPlugin implements Plugin
12
{
13
14
    /**
15
     * @var array headers that have fixed value
16
     */
17
    private $headers = [];
18
    private $removedHeader = [];
19
20
    /**
21
     * Sets a header with the given value to every requests.
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
     * @param string $name name of the header to remove
35
     */
36 2
    public function withoutHeader($name)
37
    {
38 2
        $this->removedHeader[] = $name;
39 2
    }
40
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 5
        return $next($request);
58
    }
59
}
60