Completed
Push — master ( 386195...e4192e )
by Mikael
02:20
created

Response::setJsonBody()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 0
cts 4
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
crap 2
1
<?php
2
3
namespace Anax\Response;
4
5
/**
6
 * Handling a response.
7
 */
8
class Response
9
{
10
    /**
11
    * @var array $headers    set all headers to send.
12
    * @var array $statusCode set statuscode to use.
13
    * @var array $body       body to send with response.
14
    */
15
    private $headers = [];
16
    private $statusCode;
17
    private $body;
18
19
20
21
    /**
22
     * @var array $validStatusCode these status codes are supported.
23
     */
24
    private $validStatusCode = [
25
        "200" => "HTTP/1.1 200 OK",
26
        "400" => "HTTP/1.1 400 Bad Request",
27
        "403" => "HTTP/1.1 403 Forbidden",
28
        "404" => "HTTP/1.1 404 Not Found",
29
        "405" => "HTTP/1.1 405 Method Not Allowed",
30
        "418" => "HTTP/1.1 418 I'm a teapot",
31
        "500" => "HTTP/1.1 500 Internal Server Error",
32
        "501" => "HTTP/1.1 501 Not Implemented",
33
    ];
34
35
36
37
    /**
38
     * Set status code to be sent as part of headers.
39
     *
40
     * @param string $header type of header to set
0 ignored issues
show
Bug introduced by
There is no parameter named $header. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
41
     *
42
     * @return self
43
     */
44 2
    public function setStatusCode($value)
45
    {
46 2
        if (is_null($value)) {
47
            return $this;
48
        }
49
50 2
        if (!array_key_exists($value, $this->validStatusCode)) {
51 1
            throw new Exception("Unsupported statuscode: $value");
52
        }
53
54 1
        $this->statusCode = $value;
55 1
        return $this;
56
    }
57
58
59
60
    /**
61
     * Get status code to be sent as part of headers.
62
     *
63
     * @return integer value as status code or null if not set.
64
     */
65
    public function getStatusCode()
66
    {
67
        return $this->statusCode;
68
    }
69
70
71
72
    /**
73
     * Set headers.
74
     *
75
     * @param string $header type of header to set
76
     *
77
     * @return self
78
     */
79
    public function addHeader($header)
80
    {
81
        $this->headers[] = $header;
82
        return $this;
83
    }
84
85
86
87
    /**
88
     * Check if headers are already sent and throw exception if it has,
89
     * but ignore when running in cli mode.
90
     *
91
     * @return void
92
     *
93
     * @throws Exception
94
     */
95
    public function checkIfHeadersAlreadySent()
96
    {
97
        if (php_sapi_name() !== 'cli' && headers_sent($file, $line)) {
98
            throw new Exception("Try to send headers but headers already sent, output started at $file line $line.");
99
        }
100
    }
101
102
103
104
    /**
105
     * Send headers.
106
     *
107
     * @return self
108
     */
109
    public function sendHeaders()
110
    {
111
        $this->checkIfHeadersAlreadySent();
112
113
        if (isset($this->statusCode)) {
114
            header($this->validStatusCode[$this->statusCode]);
115
        }
116
117
        foreach ($this->headers as $header) {
118
            header($header);
119
        }
120
121
        return $this;
122
    }
123
124
125
126
    /**
127
     * Set the body.
128
     *
129
     * @param callable|string $body either a string or a callable that
130
     *                              can generate the body.
131
     *
132
     * @return self
133
     */
134 1
    public function setBody($body)
135
    {
136 1
        if (is_string($body)) {
137 1
            $this->body = $body;
138 1
        } elseif (is_callable($body)) {
139
            ob_start();
140
            $res1 = call_user_func($body);
141
            $res2 = ob_get_contents();
142
            $this->body = $res2 . $res1;
143
            ob_end_clean();
144
        }
145 1
        return $this;
146
    }
147
148
149
150
    /**
151
     * Get the body.
152
     *
153
     * @return string
154
     */
155 1
    public function getBody()
156
    {
157 1
        return $this->body;
158
    }
159
160
161
162
    /**
163
     * Send response with an optional statuscode.
164
     *
165
     * @param integer $statusCode optional statuscode to send.
166
     *
167
     * @return self
168
     */
169
    public function send($statusCode = null)
170
    {
171
        $this->setStatusCode($statusCode);
172
173
        if (!headers_sent()) {
174
            $this->sendHeaders();
175
        }
176
177
        echo $this->getBody();
178
        return $this;
179
    }
180
181
182
183
    /**
184
     * Send JSON response with an optional statuscode.
185
     *
186
     * @param mixed   $data       to be encoded as json.
187
     * @param integer $statusCode optional statuscode to send.
188
     *
189
     * @return self
190
     */
191
    public function sendJson($data, $statusCode = null)
192
    {
193
        return $this->setStatusCode($statusCode)
194
                    ->setJsonBody($data)
195
                    ->send();
196
    }
197
198
199
200
    /**
201
     * Set body with JSON data.
202
     *
203
     * @param mixed $data to be encoded as json.
204
     *
205
     * @return self
206
     */
207
    public function setJsonBody($data)
208
    {
209
        $this->addHeader("Content-Type: application/json; charset=utf8");
210
        $this->setBody(json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
211
        return $this;
212
    }
213
214
215
216
    /**
217
     * Redirect to another page.
218
     *
219
     * @param string $url to redirect to
220
     *
221
     * @return void
222
     *
223
     * @SuppressWarnings(PHPMD.ExitExpression)
224
     */
225
    public function redirect($url)
226
    {
227
        $this->checkIfHeadersAlreadySent();
228
        header("Location: " . $url);
229
        exit;
230
    }
231
}
232