Completed
Push — master ( 5e45ac...a1e047 )
by John
04:04
created

HttpHeader::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Escopecz\MauticFormSubmit;
4
5
/**
6
 * HTTP Header Helper
7
 */
8
class HttpHeader
9
{
10
    /**
11
     * Key-valye paries of headers
12
     *
13
     * @var array
14
     */
15
    private $headers = [];
16
17
    /**
18
     * Key-valye paries of cookies
19
     *
20
     * @var array
21
     */
22
    private $cookies = [];
23
24
    public function __construct($textHeaders)
25
    {
26
        $this->parse($textHeaders);
27
    }
28
29
    /**
30
     * @param string $key
31
     * 
32
     * @return string|null
33
     */
34
    public function getHeaderValue($key)
35
    {
36
        return isset($this->headers[$key]) ? $this->headers[$key] : null;
37
    }
38
39
    /**
40
     * @param string $key
41
     * 
42
     * @return string|null
43
     */
44
    public function getCookieValue($key)
45
    {
46
        return isset($this->cookies[$key]) ? $this->cookies[$key] : null;
47
    }
48
49
    /**
50
     * Parse text headers and fills in cookies and headers properites
51
     *
52
     * @param string $headers
53
     */
54
    private function parse($headers)
55
    {
56
        foreach (preg_split('/\r\n|\r|\n/', $headers) as $i => $line) {
57
            if ($i === 0) {
58
                $this->headers['http_code'] = $line;
59
            } else {
60
                list($key, $value) = explode(': ', $line);
61
62
                if ($key === 'Set-Cookie') {
63
                    list($textCookie) = explode(';', $value);
64
                    list($cookieKey, $cookieValue) = explode('=', $textCookie);
65
66
                    $this->cookies[$cookieKey] = $cookieValue;
67
                } else {
68
                    $this->headers[$key] = $value;
69
                }
70
            }
71
        }
72
    }
73
}
74