Completed
Pull Request — master (#44)
by
unknown
02:34
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 Psr\Http\Message\RequestInterface;
6
7
/**
8
 * Manages http headers.
9
 */
10
class HeaderPlugin implements Plugin
11
{
12
    /**
13
     * @var array headers that have fixed value
14
     */
15
    private $headers = [];
16
    private $removedHeader = [];
17
18
    /**
19
     * Sets a header with the given value to every requests.
20
     *
21
     * @param string $name     name of the header
22
     * @param string $value    value of the header
23
     * @param bool $override   By default if the header is already set on the request the value wont be replaced
24
     * pass $override to true to make the header value the same for every request
25
     */
26 3
    public function withHeader($name, $value, $override = false)
27
    {
28 3
        $this->headers[$name] = ['value' => $value, 'override' => $override];
29 3
    }
30
31
    /**
32
     * Automatically removes the given header from the request.
33
     *
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
     * {@inheritdoc}
43
     */
44 5
    public function handleRequest(RequestInterface $request, callable $next, callable $first)
45
    {
46 5
        foreach ($this->headers as $header => $headerData) {
47 3
            if ($headerData['override'] || !$request->hasHeader($header)) {
48 2
                $request = $request->withHeader($header, $headerData['value']);
49 2
            }
50 5
        }
51 5
        foreach ($this->removedHeader as $header) {
52 2
            if ($request->hasHeader($header)) {
53 1
                $request = $request->withoutHeader($header);
54 1
            }
55 5
        }
56
57 5
        return $next($request);
58
    }
59
}
60