CResponseBasic   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 96
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 10
Bugs 2 Features 0
Metric Value
wmc 10
c 10
b 2
f 0
lcom 1
cbo 1
dl 0
loc 96
rs 10

4 Methods

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