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
|
<?php
namespace Jasny\Controller;
use Psr\Http\Message\ResponseInterface;
use Dflydev\ApacheMimeTypes\PhpRepository as ApacheMimeTypes;
/**
* Methods for a controller to send a response
*/
trait Respond
{
/**
* Get response. set for controller
*
* @return ResponseInterface
*/
abstract protected function getResponse();
/**
* Get response. set for controller
*
* @return ResponseInterface
*/
abstract protected 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($value, $header);
$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 $code HTTP status code (may be omitted)
* @param string|array $format Mime or content format
*/
public function respondWith($code, $format = null)
{
$response = $this->getResponse();
// Shift arguments if $code is omitted
if (!is_int($code) && !preg_match('/^\d{3}\b/', $code)) {
list($code, $format) = array_merge([null], func_get_args());
}
if ($code) {
$response = $response->withStatus((int)$code);
}
if ($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 optionaly redirect to created location
*
* @param string $location Url of created resource
*/
public function created($location = '')
{
$this->respondWith(201);
if ($location) {
$this->setResponseHeader('Location', $location);
}
}
/**
* Response with 204 No Content
*/
public function noContent()
{
$this->respondWith(204);
}
/**
* Redirect to url
*
* @param string $url
* @param int $code 301 (Moved Permanently), 303 (See Other) or 307 (Temporary Redirect)
*/
public function redirect($url, $code = 303)
{
$this->respondWith($code, 'text/html');
$this->setResponseHeader('Location', $url);
$urlHtml = htmlentities($url);
$this->output('You are being redirected to <a href="' . $urlHtml . '">' . $urlHtml . '</a>');
}
/**
* Redirect to previous page, or to home page
*
* @return ResponseInterface $response
*/
public function back()
{
$this->redirect($this->getLocalReferer() ?: '/');
}
/**
* 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 = "Forbidden")
{
$this->respondWith(403);
$this->output($message);
}
/**
* Respond with 404 Not Found
*
* @param string $message
* @param int $code HTTP status code (404 or 405)
*/
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)
{
if (\Jasny\str_contains($format, '/')) { // Already MIME
return $format;
}
$repository = new ApacheMimeTypes();
$mime = $repository->findType('html');
if (!isset($mime)) {
throw new \UnexpectedValueException("Format $format doesn't correspond with a MIME type");
}
return $mime;
}
/**
* Serialize data
*
* @param mixed $data
* @param string $contentType
* @return string
*/
protected function serializeData($data, $contentType)
{
if ($contentType == 'json') {
return (is_string($data) && (json_decode($data) !== null || !json_last_error()))
? $data : json_encode($data);
}
if (!is_scalar($data)) {
throw new \Exception("Unable to serialize data to {$contentType}");
}
return $data;
}
/**
* Output result
*
* @param mixed $data
* @param string $format Output format as MIME or extension
*/
public function output($data, $format = null)
{
if (!isset($format)) {
$contentType = $this->getResponse()->getHeaderLine('Content-Type') ?: 'text/html';
} else {
$contentType = $this->getContentType($format);
$this->setResponseHeader('Content-Type', $contentType);
}
$content = $this->serializeData($data, $contentType);
$this->getResponse()->getBody()->write($content);
}
}
|