CResponseBasic::checkIfHeadersAlreadySent()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 2
eloc 3
c 1
b 0
f 1
nc 2
nop 0
dl 0
loc 6
rs 9.4285
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("Trying 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();
0 ignored issues
show
Coding Style Compatibility introduced by
The method redirect() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
101
    }
102
}
103