Passed
Push — master ( 45e27a...3ebd61 )
by Radu
01:14
created

HttpResponse::sendHeaders()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 11
nc 3
nop 0
dl 0
loc 18
rs 9.2
c 0
b 0
f 0
1
<?php
2
namespace WebServCo\Framework;
3
4
use WebServCo\Framework\Http;
5
6
final class HttpResponse extends \WebServCo\Framework\AbstractResponse implements
7
    \WebServCo\Framework\Interfaces\ResponseInterface
8
{
9
    protected $statusText;
10
    protected $headers;
11
    protected $charset;
12
13
    public function __construct($content = null, $statusCode = 200, $headers = [])
14
    {
15
        $this->setStatus($statusCode);
16
17
        $this->charset = 'utf-8';
18
19
        foreach ($headers as $name => $value) {
20
            $this->setHeader($name, $value);
21
        }
22
23
        $this->setContent($content);
24
    }
25
26
    public function getHeaders()
27
    {
28
        return $this->headers;
29
    }
30
31
    public function setStatus($statusCode)
32
    {
33
        if (!isset(Http::$statusCodes[$statusCode])) {
34
                throw new \WebServCo\Framework\Exceptions\ApplicationException(
35
                    sprintf('Invalid HTTP status code: %s', $statusCode)
36
                );
37
        }
38
        $this->statusCode = $statusCode;
39
        $this->statusText = Http::$statusCodes[$statusCode];
40
    }
41
42
    public function setHeader($name, $value)
43
    {
44
        switch ($name) {
45
            case 'Content-Type':
46
                $this->headers[$name] = $value . '; charset=' . $this->charset;
47
                break;
48
            default:
49
                $this->headers[$name] = $value;
50
                break;
51
        }
52
    }
53
54
    public function send()
55
    {
56
        $this->sendHeaders();
57
        $this->sendContent();
58
        return $this->statusCode;
59
    }
60
61
    protected function sendHeader($name, $value, $statusCode)
62
    {
63
        header(
64
            sprintf('%s: %s', $name, $value),
65
            true,
66
            $statusCode
67
        );
68
        return true;
69
    }
70
71
    protected function sendHeaders()
72
    {
73
        foreach ($this->headers as $name => $value) {
74
            if (is_array($value)) {
75
                foreach ($value as $item) {
76
                    $this->sendHeader($name, $item, $this->statusCode);
77
                }
78
            } else {
79
                $this->sendHeader($name, $value, $this->statusCode);
80
            }
81
        }
82
83
        $this->sendHeader('Content-length', strlen($this->content), $this->statusCode);
84
85
        header(
86
            sprintf('HTTP/1.1 %s %s', $this->statusCode, $this->statusText),
87
            true,
88
            $this->statusCode
89
        );
90
    }
91
92
    protected function sendContent()
93
    {
94
        echo $this->content;
95
    }
96
}
97