CResponseBasic::sendHeaders()   B
last analyzed

Complexity

Conditions 6
Paths 6

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
nc 6
nop 0
dl 0
loc 29
ccs 0
cts 19
cp 0
crap 42
rs 8.8337
c 0
b 0
f 0
1
<?php
2
3
namespace Anax\Response;
4
5
/**
6
 * Handling a response.
7
 *
8
 */
9
class CResponseBasic
10
{
11
12
13
    /**
14
    * Properties
15
    *
16
    */
17
    private $headers; // Set all headers to send
18
19
20
21
    /**
22
     * Set headers.
23
     *
24
     * @param string $header type of header to set
25
     *
26
     * @return $this
27
     */
28
    public function setHeader($header)
29
    {
30
        $this->headers[] = $header;
31
    }
32
33
34
35
    /**
36
     * Check if headers are already sent and throw exception if it is.
37
     *
38
     * @return void
39
     *
40
     * @throws \Exception
41
     */
42
    public function checkIfHeadersAlreadySent()
43
    {
44
        if (headers_sent($file, $line)) {
45
            throw new \Exception("Try to send headers but headers already sent, output started at $file line $line.");
46
        }
47
    }
48
49
50
51
    /**
52
     * Send headers.
53
     *
54
     * @return $this
55
     */
56
    public function sendHeaders()
57
    {
58
        if (empty($this->headers)) {
59
            return;
60
        }
61
62
        $this->checkIfHeadersAlreadySent();
63
64
        foreach ($this->headers as $header) {
65
            switch ($header) {
66
                case '403':
67
                    header('HTTP/1.0 403 Forbidden');
68
                    break;
69
70
                case '404':
71
                    header('HTTP/1.0 404 Not Found');
72
                    break;
73
74
                case '500':
75
                    header('HTTP/1.0 500 Internal Server Error');
76
                    break;
77
78
                default:
79
                    throw new \Exception("Trying to sen unkown header type: '$header'.");
80
            }
81
        }
82
83
        return $this;
84
    }
85
86
87
88
    /**
89
     * Redirect to another page.
90
     *
91
     * @param string $url to redirect to
92
     *
93
     * @return void
94
     */
95
    public function redirect($url)
96
    {
97
        $this->checkIfHeadersAlreadySent();
98
99
        header('Location: ' . $url);
100
        exit();
101
    }
102
}
103