Completed
Pull Request — master (#100)
by Maxime
02:21
created

AbstractHttpMessage::initHeaders()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 0
cts 7
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 2
crap 6
1
<?php
2
/**
3
 * This file is a part of a nekland library
4
 *
5
 * (c) Nekland <[email protected]>
6
 *
7
 * For the full license, take a look to the LICENSE file
8
 * on the root directory of this project
9
 */
10
11
namespace Nekland\Woketo\Http;
12
13
14
use Nekland\Woketo\Exception\Http\HttpException;
15
16
abstract class AbstractHttpMessage
17
{
18
    /**
19
     * @var HttpHeadersBag
20
     */
21
    private $headers;
22
23
    /**
24
     * @var string for example "HTTP/1.1"
25
     */
26
    private $httpVersion;
27
28
    /**
29
     * @param string $httpVersion
30
     * @return self
31
     */
32
    protected function setHttpVersion($httpVersion)
33
    {
34
        $this->httpVersion = $httpVersion;
35
36
        return $this;
37
    }
38
39
    /**
40
     * @param string $name
41
     * @param string $value
42
     * @return self
43
     */
44
    public function addHeader(string $name, string $value)
45
    {
46
        if (null === $this->headers) {
47
            $this->headers = new HttpHeadersBag();
48
        }
49
        $this->headers->add($name, $value);
50
51
        return $this;
52
    }
53
54
    /**
55
     * @param string $header
56
     * @param mixed  $default
57
     * @return string
58
     */
59
    public function getHeader(string $header, $default = null)
60
    {
61
        return $this->headers[$header] ?: $default;
62
    }
63
64
    /**
65
     * @return string
66
     */
67
    public function getHttpVersion()
68
    {
69
        return $this->httpVersion;
70
    }
71
72
    /**
73
     * @return array|HttpHeadersBag
74
     */
75
    public function getHeaders()
76
    {
77
        return $this->headers ?: new HttpHeadersBag();
78
    }
79
80
    /**
81
     * @param string[]              $headers
82
     * @param AbstractHttpMessage   $request
83
     */
84
    protected static function initHeaders(array $headers, AbstractHttpMessage $request)
85
    {
86
        foreach ($headers as $header) {
87
            $cuttedHeader = \explode(':', $header);
88
            $request->addHeader(\trim($cuttedHeader[0]), trim(str_replace($cuttedHeader[0] . ':', '', $header)));
89
        }
90
    }
91
92
    protected static function createNotHttpException($line)
93
    {
94
        return new HttpException(
95
            \sprintf('The message is not an http request. "%s" received.', $line)
96
        );
97
    }
98
}
99