summaryrefslogtreecommitdiffstats
path: root/src/Controller/Output.php
blob: 8eecc8b7857c4b3892c92b87de1a54da41ab59b2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
<?php

namespace Jasny\Controller;

use Psr\Http\Message\ResponseInterface;
use Dflydev\ApacheMimeTypes\PhpRepository as ApacheMimeTypes;

/**
 * Methods for a controller to send a response
 */
trait Output
{
    /**
     * @var string
     */
    protected $defaultFormat;
    
    /**
     * Get response. set for controller
     *
     * @return ResponseInterface
     */
    abstract public function getResponse();

    /**
     * Get response. set for controller
     *
     * @return ResponseInterface
     */
    abstract public function setResponse(ResponseInterface $response);

    /**
     * Returns the HTTP referer if it is on the current host
     *
     * @return string
     */
    abstract public function getLocalReferer();
    
    
    /**
     * Set a response header
     * 
     * @param string  $header
     * @param string  $value
     * @param boolean $overwrite
     */
    public function setResponseHeader($header, $value, $overwrite = true)
    {
        $fn = $overwrite ? 'withHeader' : 'withAddedHeader';
        $response = $this->getResponse()->$fn($header, $value);
        
        $this->setResponse($response);
    }
    
    /**
     * Set the headers with HTTP status code and content type.
     * @link http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
     * 
     * Examples:
     * <code>
     *   $this->respondWith(200, 'json');
     *   $this->respondWith(200, 'application/json');
     *   $this->respondWith(204);
     *   $this->respondWith("204 Created");
     *   $this->respondWith('json');
     * </code>
     * 
     * @param int|string   $status  HTTP status (may be omitted)
     * @param string|array $format  Mime or content format
     */
    public function respondWith($status, $format = null)
    {
        $response = $this->getResponse();

        // Shift arguments if $code is omitted
        if (isset($status) && !is_int($status) && (!is_string($status) || !preg_match('/^\d{3}\b/', $status))) {
            list($status, $format) = array_merge([null], func_get_args());
        }

        if (!empty($status)) {
            list($code, $phrase) = explode(' ', $status, 2) + [1 => null];
            $response = $response->withStatus((int)$code, $phrase);
        }
        
        if (!empty($format)) {
            $contentType = $this->getContentType($format);
            $response = $response->withHeader('Content-Type', $contentType);   
        }

        $this->setResponse($response);
    }

    
    /**
     * Response with 200 OK
     *
     * @return ResponseInterface $response
     */
    public function ok()
    {
        $this->respondWith(200);
    }

    /**
     * Response with created 201 code, and optionally the created location
     *
     * @param string $location  Url of created resource
     */
    public function created($location = null)
    {
        $this->respondWith(201);

        if (!empty($location)) {
            $this->setResponseHeader('Location', $location);
        }
    }

    /**
     * Response with 203 Accepted
     */
    public function accepted()
    {
        $this->respondWith(202);
    }

    /**
     * Response with 204 No Content
     * 
     * @param int $code  204 (No Content) or 205 (Reset Content)
     */
    public function noContent($code = 204)
    {
        $this->respondWith($code);
    }
    
    /**
     * Respond with a 206 Partial content with `Content-Range` header
     * 
     * @param int $rangeFrom  Beginning of the range in bytes
     * @param int $rangeTo    End of the range in bytes
     * @param int $totalSize  Total size in bytes
     */
    public function partialContent($rangeFrom, $rangeTo, $totalSize)
    {
        $this->respondWith(206);
        
        $this->setResponseHeader('Content-Range', "bytes {$rangeFrom}-{$rangeTo}/{$totalSize}");
        $this->setResponseHeader('Content-Length', $rangeTo - $rangeFrom);
    }

    
    /**
     * Redirect to url and output a short message with the link
     *
     * @param string $url
     * @param int    $code  301 (Moved Permanently), 302 (Found), 303 (See Other) or 307 (Temporary Redirect)
     */
    public function redirect($url, $code = 303)
    {
        $this->respondWith($code);
        $this->setResponseHeader('Location', $url);
        
        $urlHtml = htmlentities($url);
        $this->output('You are being redirected to <a href="' . $urlHtml . '">' . $urlHtml . '</a>', 'text/html');
    }

    /**
     * Redirect to previous page, or to home page
     *
     * @return ResponseInterface $response
     */
    public function back()
    {
        $this->redirect($this->getLocalReferer() ?: '/');
    }
    
    /**
     * Respond with 304 Not Modified
     */
    public function notModified()
    {
        $this->respondWith(304);
    }

    
    /**
     * Respond with 400 Bad Request
     *
     * @param string $message
     * @param int    $code     HTTP status code
     */
    public function badRequest($message, $code = 400)
    {
        $this->respondWith($code);
        $this->output($message);
    }

    /**
     * Respond with a 401 Unauthorized
     */
    public function requireAuth()
    {
        $this->respondWith(401);
    }

    /**
     * Alias of requireAuth
     * @deprecated
     */
    final public function requireLogin()
    {
        $this->requireAuth();
    }
    
    /**
     * Respond with 402 Payment Required
     *
     * @param string $message
     */
    public function paymentRequired($message = "Payment required")
    {
        $this->respondWith(402);
        $this->output($message);
    }

    /**
     * Respond with 403 Forbidden
     *
     * @param string $message
     */
    public function forbidden($message = "Access denied")
    {
        $this->respondWith(403);
        $this->output($message);
    }

    /**
     * Respond with 404 Not Found
     *
     * @param string $message
     * @param int    $code     404 (Not Found), 405 (Method not allowed) or 410 (Gone)
     */
    public function notFound($message = "Not found", $code = 404)
    {
        $this->respondWith($code);
        $this->output($message);
    }

    /**
     * Respond with 409 Conflict
     *
     * @param string $message
     */
    public function conflict($message)
    {
        $this->respondWith(409);
        $this->output($message);
    }

    /**
     * Respond with 429 Too Many Requests
     *
     * @param string $message
     */
    public function tooManyRequests($message = "Too many requests")
    {
        $this->respondWith(429);
        $this->output($message);
    }

    
    /**
     * Respond with a server error
     *
     * @param string $message
     * @param int    $code     HTTP status code
     */
    public function error($message = "An unexpected error occured", $code = 500)
    {
        $this->respondWith($code);
        $this->output($message);
    }
    
    
    /**
     * Get MIME type for extension
     *
     * @param string $format
     * @return string
     */
    protected function getContentType($format)
    {
        // Check if it's already MIME
        if (\Jasny\str_contains($format, '/')) {
            return $format;
        }
        
        $repository = new ApacheMimeTypes();
        $mime = $repository->findType($format);

        if (!isset($mime)) {
            throw new \UnexpectedValueException("Format '$format' doesn't correspond with a MIME type");
        }
        
        return $mime;
    }
    
    
    /**
     * If a non scalar value is passed without an format, use this format
     * 
     * @param string $format  Format by extention or MIME
     */
    public function byDefaultSerializeTo($format)
    {
        $this->defaultFormat = $format;
    }
    
    /**
     * Serialize data
     * 
     * @param mixed  $data
     * @param string $contentType
     * @return string
     */
    protected function serializeData($data, $contentType)
    {
        if (is_string($data)) {
            return $data;
        }
        
        $repository = new ApacheMimeTypes();
        list($format) = $repository->findExtensions($contentType) + [null];
        
        $method = 'serializeDataTo' . $format;
        
        if (method_exists($this, $method)) {
            return $this->$method($data);
        }

        $type = (is_object($data) ? get_class($data) . ' ' : '') . gettype($data);
        throw new \UnexpectedValueException("Unable to serialize $type to '$contentType'");
    }
    
    /**
     * Serialize data to JSON
     * @internal made private because this will likely move to a library
     * 
     * @param mixed $data
     * @return string
     */
    private function serializeDataToJson($data)
    {
        return json_encode($data);
    }
    
    /**
     * Serialize data to XML.
     * @internal made private because this will likely move to a library
     * 
     * @param mixed $data
     * @return string
     */
    private function serializeDataToXml($data)
    {
        if ($data instanceof \SimpleXMLElement) {
            return $data->asXML();
        }
        
        if (($data instanceof \DOMNode && isset($data->ownerDocument)) || $data instanceof \DOMDocument) {
            $dom = $data instanceof \DOMDocument ? $data : $data->ownerDocument;
            return $dom->saveXML($data);
        }
        
        $type = (is_object($data) ? get_class($data) . ' ' : '') . gettype($data);
        throw new \UnexpectedValueException("Unable to serialize $type to XML");
    }

    /**
     * Set the content type for the output
     * 
     * @param string $format
     * @return string
     */
    protected function outputContentType($format)
    {
        if (!isset($format)) {
            $contentType = $this->getResponse()->getHeaderLine('Content-Type');
            
            if (empty($contentType)) {
                $format = $this->defaultFormat ?: 'text/html';
            }
        }
        
        if (empty($contentType)) {
            $contentType = $this->getContentType($format);
            $this->setResponseHeader('Content-Type', $contentType);
        }
        
        return $contentType;
    }
    
    /**
     * Output result
     *
     * @param mixed  $data
     * @param string $format  Output format as MIME or extension
     */
    public function output($data, $format = null)
    {
        $contentType = $this->outputContentType($format);

        try {
            $content = $this->serializeData($data, $contentType);
        } catch (\UnexpectedValueException $e) {
            if (!isset($format) && isset($this->defaultFormat) && $this->defaultFormat !== $contentType) {
                $this->output($data, $this->defaultFormat); // Try default format instead
                return;
            }
            
            throw $e;
        }

        $this->getResponse()->getBody()->write($content);
    }
}