Passed
Push — master ( 01946f...5bb132 )
by Mikael
02:52
created

Response::sendFile()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 0
cts 6
cp 0
rs 9.9332
c 0
b 0
f 0
cc 3
nc 2
nop 0
crap 12
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 string $body       body to send with response.
14
    * @var string $filename   a filename to send for download.
15
    */
16
    private $headers = [];
17
    private $statusCode = null;
18
    private $body = null;
19
    private $filename = null;
20
21
22
23
    /**
24
     * Set status code to be sent as part of headers.
25
     *
26
     * @param int $value of response status code
27
     *
28
     * @return self
29
     */
30 14
    public function setStatusCode(int $value = null)
31
    {
32 14
        if (is_null($value)) {
33 6
            return $this;
34
        }
35
36 8
        $this->statusCode = $value;
37 8
        return $this;
38
    }
39
40
41
42
    /**
43
     * Get status code to be sent as part of headers.
44
     *
45
     * @return integer value as status code or null if not set.
46
     */
47 7
    public function getStatusCode()
48
    {
49 7
        return $this->statusCode;
50
    }
51
52
53
54
    /**
55
     * Set headers.
56
     *
57
     * @param string $header type of header to set
58
     *
59
     * @return self
60
     */
61 7
    public function addHeader($header)
62
    {
63 7
        $this->headers[] = $header;
64 7
        return $this;
65
    }
66
67
68
69
    /**
70
     * Get all headers.
71
     *
72
     * @return array with headers
73
     */
74 1
    public function getHeaders() : array
75
    {
76 1
        return $this->headers;
77
    }
78
79
80
81
    /**
82
     * Send headers.
83
     *
84
     * @return self
85
     */
86 1
    public function sendHeaders()
87
    {
88 1
        if (php_sapi_name() !== "cli" && headers_sent($file, $line)) {
89
            throw new Exception("Try to send headers but headers already sent, output started at $file line $line.");
90
        }
91
92 1
        http_response_code($this->statusCode);
93
94 1
        foreach ($this->headers as $header) {
95 1
            if (php_sapi_name() !== "cli") {
96 1
                header($header);
97
            }
98
        }
99
100 1
        return $this;
101
    }
102
103
104
105
    /**
106
     * Set the body.
107
     *
108
     * @param callable|string $body either a string or a callable that
109
     *                              can generate the body.
110
     *
111
     * @return self
112
     */
113 8
    public function setBody($body)
114
    {
115 8
        if (is_string($body)) {
116 7
            $this->body = $body;
117 3
        } elseif (is_array($body)) {
118 2
            $this->setJsonBody($body);
119 1
        } elseif (is_callable($body)) {
120 1
            ob_start();
121 1
            $res1 = call_user_func($body);
122 1
            $res2 = ob_get_contents();
123 1
            $this->body = $res2 . $res1;
124 1
            ob_end_clean();
125
        }
126 8
        return $this;
127
    }
128
129
130
131
    /**
132
     * Get the body.
133
     *
134
     * @return string
135
     */
136 8
    public function getBody()
137
    {
138 8
        return $this->body;
139
    }
140
141
142
143
    /**
144
     * Send a file to be downloaded by the user.
145
     *
146
     * @param string $filename to the file to download.
147
     *
148
     * @return self
149
     */
150
    public function addFile(string $filename) : object
151
    {
152
        $this->filename = $filename;
153
154
        // Get file type and set it as Content Type
155
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
156
        header("Content-Type: " . finfo_file($finfo, $filename));
157
        finfo_close($finfo);
158
159
        // Use Content-Disposition: attachment to specify the filename
160
        $this->addHeader("Content-Disposition: attachment; filename="
161
            . basename($filename));
162
163
        // No cache
164
        $this->addHeader("Expires: 0");
165
        $this->addHeader("Cache-Control: must-revalidate");
166
        $this->addHeader("Pragma: public");
167
168
        // Define file size
169
        $this->addHeader("Content-Length: "
170
            . filesize($filename));
171
172
        return $this;
173
    }
174
175
176
177
    /**
178
     * Send a file to be downloaded by the user.
179
     *
180
     * @param string $filename to the file to download.
0 ignored issues
show
Bug introduced by
There is no parameter named $filename. 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...
181
     *
182
     * @return self
183
     */
184
    public function sendFile() : object
185
    {
186
        ob_clean();
187
        flush();
188
        if ($this->filename && is_readable($this->filename)) {
189
            readfile($this->filename);
190
        }
191
192
        return $this;
193
    }
194
195
196
197
    /**
198
     * Send response supporting several ways of receiving response $data.
199
     *
200
     * @param mixed $data to use as optional base for creating response.
201
     *
202
     * @return self
203
     */
204 6
    public function send($data = null)
205
    {
206 6
        $statusCode = null;
207
208 6
        if ($data instanceof self) {
209 1
            return $data->send();
210
        }
211
212 6
        if (is_string($data)) {
213 1
            $this->setBody($data);
214
        }
215
216 6
        if (is_array($data) && isset($data[0])) {
217 2
            $this->setBody($data[0]);
218
        }
219
220 6
        if (is_array($data) && isset($data[1]) && is_numeric($data[1])) {
221 1
            $statusCode = $data[1];
222
        }
223
224 6
        $this->setStatusCode($statusCode);
225
226 6
        if (!headers_sent()) {
227
            $this->sendHeaders();
228
        }
229
230 6
        if ($this->body) {
231 5
            echo $this->getBody();
232
        }
233
234 6
        if ($this->filename) {
235
            $this->sendFile();
236
        }
237
238 6
        return $this;
239
    }
240
241
242
243
    /**
244
     * Send JSON response with an optional statuscode.
245
     *
246
     * @param mixed   $data       to be encoded as json.
247
     * @param integer $statusCode optional statuscode to send.
248
     *
249
     * @return self
250
     */
251 1
    public function sendJson($data, $statusCode = null)
252
    {
253 1
        return $this->setStatusCode($statusCode)
254 1
                    ->setJsonBody($data)
255 1
                    ->send();
256
    }
257
258
259
260
    /**
261
     * Set body with JSON data.
262
     *
263
     * @param mixed $data to be encoded as json.
264
     *
265
     * @return self
266
     */
267 3
    public function setJsonBody($data)
268
    {
269 3
        $this->addHeader("Content-Type: application/json; charset=utf8");
270 3
        $this->setBody(json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
271 3
        return $this;
272
    }
273
274
275
276
    /**
277
     * Redirect to another page.
278
     *
279
     * @param string $url to redirect to
280
     *
281
     * @return self
282
     */
283 2
    public function redirect(string $url) : object
284
    {
285 2
        $this->addHeader("Location: " . $url);
286 2
        $this->body = null;
287 2
        return $this;
288
    }
289
}
290