-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathResponse.php
More file actions
750 lines (698 loc) · 21.7 KB
/
Response.php
File metadata and controls
750 lines (698 loc) · 21.7 KB
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
<?php
// This file is part of Minz.
// Copyright 2020-2026 Marien Fressinaud
// SPDX-License-Identifier: AGPL-3.0-or-later
namespace Minz;
use Minz\Output;
/**
* The Response represents the answer given to a Request. It is returned to a client.
*
* The response is initialized and returned by a controller action. It contains
* a status code, headers and optional cookies and output.
*
* The code must be a valid HTTP code, even in CLI mode.
*
* A response almost always declares a Content-Type and a Content-Security-Policy
* headers (except when it's not pertinent).
*
* An Output can be attached to a Response. The output is in charge of
* generating the content to return to the client. There are four different
* outputs implementing the Output interface:
*
* - \Minz\Output\File: to serve a file;
* - \Minz\Output\Json: to render Json;
* - \Minz\Output\Text: to render text;
* - \Minz\Output\Template: to generate more complex structures (e.g. HTML)
* based on either a simple template system, or on a Twig template system.
*
* For instance, to generate a text response:
*
* ```php
* $text_output = new \Minz\Output\Text('some text');
* $response = new Response(200, $text_output);
*
* // Can be shortened in
* $response = Response::text(200, 'some text');
* ```
*
* Or to generate a HTML response:
*
* ```php
* $template_output = new Output\Template('pointer/to/template.phtml', [
* 'foo' => 'bar',
* ]);
* $response = new Response(200, $template_output);
*
* // Can be shortened in
* $response = Response::ok('path/to/template.phtml', [
* 'foo' => 'bar',
* ]);
* ```
*
* You most probably want to use the short versions to generate responses since
* they are a lot easier to use. It’s important to know the mechanics though.
* It can be useful to create new kind of outputs for instance.
*
* @see \Minz\Output
* @see \Minz\Output\File
* @see \Minz\Output\Json
* @see \Minz\Output\Text
* @see \Minz\Output\Template
*
* The responses are returned to the calling script which must generate the
* corresponding headers, cookies and content. For instance, in `public/index.php`:
*
* ```php
* $application = new \App\Application();
* $response = $application->run($request);
*
* http_response_code($response->code());
*
* foreach ($response->cookies() as $cookie) {
* setcookie($cookie['name'], $cookie['value'], $cookie['options']);
* }
*
* foreach ($response->headers() as $header) {
* header($header);
* }
*
* echo $response->render();
*
* // Can be shortened in
* \Minz\Response::sendByHttp($response);
* ```
*
* In a CLI script, it is quite different since cookies and headers aren't
* relevant:
*
* ```php
* $application = new \App\Application();
* $response = $application->run($request);
*
* echo $response->render() . "\n";
*
* $code = $response->code();
* if ($code >= 200 && $code < 300) {
* exit(0);
* } else {
* exit(1);
* }
*
* // Can be shortened in
* \Minz\Response::sendToCli($response);
* ```
*
* @phpstan-import-type RouteName from Router
* @phpstan-import-type UrlParameters from Url
* @phpstan-import-type TemplateName from Template\TemplateInterface
* @phpstan-import-type TemplateContext from Template\TemplateInterface
*
* @phpstan-type ResponseHttpCode value-of<Response::VALID_HTTP_CODES>
* @phpstan-type ResponseHeaders array<string, ResponseHeader>
* @phpstan-type ResponseHeader string|array<string, string>
* @phpstan-type ResponseCookies array<string, ResponseCookie>
* @phpstan-type ResponseCookie array{
* 'name': string,
* 'value': string,
* 'options': array{
* 'expires': int,
* 'path': string,
* 'secure': bool,
* 'httponly': bool,
* 'samesite': 'Strict'|'Lax'|'None',
* 'domain'?: string,
* },
* }
* @phpstan-type CookieOptions array{
* 'expires'?: int,
* 'path'?: string,
* 'secure'?: bool,
* 'httponly'?: bool,
* 'samesite'?: 'Strict'|'Lax'|'None',
* 'domain'?: string,
* }
* @phpstan-type ResponseGenerator \Generator<int, Response, void, void>
* @phpstan-type ResponseReturnable Response|ResponseGenerator
*/
class Response
{
public const VALID_HTTP_CODES = [
100, 101,
200, 201, 202, 203, 204, 205, 206,
300, 301, 302, 303, 304, 305, 306, 307,
400, 401, 402, 403, 404, 405, 406, 407, 408, 409,
410, 411, 412, 413, 414, 415, 416, 417,
500, 501, 502, 503, 504, 505,
];
public const DEFAULT_CSP = [
'default-src' => "'self'",
];
/** @var ResponseHttpCode */
private int $code;
/** @var ResponseHeaders */
private array $headers = [];
/** @var ResponseCookies */
private array $cookies = [];
private ?Output $output;
/**
* Create a OK response (HTTP 200) with an optional Output\Template.
*
* @see \Minz\Output\Template
*
* @param ?TemplateName $name
* @param TemplateContext $context
*
* @throws \Minz\Errors\OutputError
* Raised if the template file doesn't exist.
*/
public static function ok(?string $name = null, array $context = []): Response
{
if ($name) {
$template_output = new Output\Template($name, $context);
} else {
$template_output = null;
}
return new Response(200, $template_output);
}
/**
* Create a created response (HTTP 201) with an optional Output\Template.
*
* @see \Minz\Output\Template
*
* @param ?TemplateName $name
* @param TemplateContext $context
*
* @throws \Minz\Errors\OutputError
* Raised if the template file doesn't exist.
*/
public static function created(?string $name = null, array $context = []): Response
{
if ($name) {
$template_output = new Output\Template($name, $context);
} else {
$template_output = null;
}
return new Response(201, $template_output);
}
/**
* Create an accepted response (HTTP 202) with an optional Output\Template.
*
* @see \Minz\Output\Template
*
* @param ?TemplateName $name
* @param TemplateContext $context
*
* @throws \Minz\Errors\OutputError
* Raised if the template file doesn't exist.
*/
public static function accepted(?string $name = null, array $context = []): Response
{
if ($name) {
$template_output = new Output\Template($name, $context);
} else {
$template_output = null;
}
return new Response(202, $template_output);
}
/**
* Create a no content response (HTTP 204).
*/
public static function noContent(): Response
{
return new Response(204);
}
/**
* Create a moved permanently response (HTTP 301).
*/
public static function movedPermanently(string $url): Response
{
$response = new Response(301);
$response->setHeader('Location', $url);
return $response;
}
/**
* Create a found response (HTTP 302).
*/
public static function found(string $url): Response
{
$response = new Response(302);
$response->setHeader('Location', $url);
return $response;
}
/**
* Create a found response (HTTP 302) to an action pointer.
*
* It is a shortcut to generate internal redirections. For instance:
*
* ```php
* // In Application.php
* $router = new \Minz\Router();
* $router->addRoute('get', '/', 'Pages#Home', 'home');
* \Minz\Url::setRouter($router);
*
* // In a controller action
* $response = \Minz\Response::redirect('home');
* ```
*
* @param RouteName $name
* @param UrlParameters $parameters
*/
public static function redirect(string $name, array $parameters = []): Response
{
$url = Url::for($name, $parameters);
return self::found($url);
}
/**
* Create a bad request response (HTTP 400) with an optional Output\Template.
*
* @see \Minz\Output\Template
*
* @param ?TemplateName $name
* @param TemplateContext $context
*
* @throws \Minz\Errors\OutputError
* Raised if the template file doesn't exist.
*/
public static function badRequest(?string $name = null, array $context = []): Response
{
if ($name) {
$template_output = new Output\Template($name, $context);
} else {
$template_output = null;
}
return new Response(400, $template_output);
}
/**
* Create an unauthorized response (HTTP 401) with an optional Output\Template.
*
* @see \Minz\Output\Template
*
* @param ?TemplateName $name
* @param TemplateContext $context
*
* @throws \Minz\Errors\OutputError
* Raised if the template file doesn't exist.
*/
public static function unauthorized(?string $name = null, array $context = []): Response
{
if ($name) {
$template_output = new Output\Template($name, $context);
} else {
$template_output = null;
}
return new Response(401, $template_output);
}
/**
* Create a forbidden response (HTTP 403) with an optional Output\Template.
*
* @see \Minz\Output\Template
*
* @param ?TemplateName $name
* @param TemplateContext $context
*
* @throws \Minz\Errors\OutputError
* Raised if the template file doesn't exist.
*/
public static function forbidden(?string $name = null, array $context = []): Response
{
if ($name) {
$template_output = new Output\Template($name, $context);
} else {
$template_output = null;
}
return new Response(403, $template_output);
}
/**
* Create a not found response (HTTP 404) with an optional Output\Template.
*
* @see \Minz\Output\Template
*
* @param ?TemplateName $name
* @param TemplateContext $context
*
* @throws \Minz\Errors\OutputError
* Raised if the template file doesn't exist.
*/
public static function notFound(?string $name = null, array $context = []): Response
{
if ($name) {
$template_output = new Output\Template($name, $context);
} else {
$template_output = null;
}
return new Response(404, $template_output);
}
/**
* Create an internal server error response (HTTP 500) with an optional Output\Template.
*
* @see \Minz\Output\Template
*
* @param ?TemplateName $name
* @param TemplateContext $context
*
* @throws \Minz\Errors\OutputError
* Raised if the template file doesn't exist.
*/
public static function internalServerError(?string $name = null, array $context = []): Response
{
if ($name) {
$template_output = new Output\Template($name, $context);
} else {
$template_output = null;
}
return new Response(500, $template_output);
}
/**
* Create a text response with the given HTTP code.
*
* @see \Minz\Output\Text
*
* @param ResponseHttpCode $code
*/
public static function text(int $code, string $text): Response
{
$output = new \Minz\Output\Text($text);
return new Response($code, $output);
}
/**
* Create a Json response with the given HTTP code.
*
* @see https://www.php.net/manual/function.json-encode.php
*
* @param ResponseHttpCode $code
* @param mixed[] $values
*/
public static function json(int $code, array $values): Response
{
$output = new \Minz\Output\Json($values);
return new Response($code, $output);
}
/**
* Create a Response from a HTTP status code and an optional output.
*
* @param ResponseHttpCode $code
*
* @throws \Minz\Errors\ResponseError
* Raised if the code is not a valid HTTP status code.
*/
public function __construct(int $code, ?Output $output = null)
{
$this->setCode($code);
$this->setOutput($output);
if ($output) {
$content_type = $output->contentType();
} else {
$content_type = 'text/plain';
}
$this->setHeader('Content-Type', $content_type);
$this->setHeader('Content-Security-Policy', self::DEFAULT_CSP);
}
public function output(): ?Output
{
return $this->output;
}
public function setOutput(?Output $output): void
{
$this->output = $output;
}
/**
* @return ResponseHttpCode
*/
public function code(): int
{
return $this->code;
}
/**
* @param ResponseHttpCode $code
*
* @throws \Minz\Errors\ResponseError
* Raised if the code is not a valid HTTP status code.
*/
public function setCode(int $code): void
{
if (!in_array($code, self::VALID_HTTP_CODES)) {
throw new Errors\ResponseError("{$code} is not a valid HTTP code.");
}
$this->code = $code;
}
/**
* Add or replace a HTTP header.
*
* @param ResponseHeader $value
*/
public function setHeader(string $name, mixed $value): void
{
$this->headers[$name] = $value;
}
/**
* Change sources of a Content-Security-Policy directive.
*
* `Content-Security-Policy` header allows to control resources a client is
* allowed to load.
*
* @see https://developer.mozilla.org/docs/Web/HTTP/Headers/Content-Security-Policy
*/
public function setContentSecurityPolicy(string $directive, string $sources): void
{
if (!is_array($this->headers['Content-Security-Policy'])) {
$this->headers['Content-Security-Policy'] = [];
}
$this->headers['Content-Security-Policy'][$directive] = $sources;
}
/**
* Add sources to a Content-Security-Policy directive.
*
* Contrary to the setContentSecurityPolicy, it doesn't override the
* previous directive.
*/
public function addContentSecurityPolicy(string $directive, string $sources): void
{
if (!is_array($this->headers['Content-Security-Policy'])) {
$this->headers['Content-Security-Policy'] = [];
}
$previous_sources = $this->headers['Content-Security-Policy'][$directive] ?? '';
$sources = trim($previous_sources . ' ' . $sources);
$this->setContentSecurityPolicy($directive, $sources);
}
/**
* Return the headers of the Response.
*
* Headers can be returned as strings via the `$raw` parameter in order to
* be passed to the PHP `header()` function. For instance:
*
* ```php
* $response->setHeader('Content-Type', 'text/plain');
* $response->setContentSecurityPolicy('default-src', "'self'");
* $response->setContentSecurityPolicy('style-src', "'self' 'unsafe-inline'");
*
* $response->headers(true);
* // will return
* [
* 'Content-Type' => 'text/plain',
* 'Content-Security-Policy' => [
* 'default-src' => "'self'",
* 'style-src' => "'self' 'unsafe-inline'",
* ],
* ]
*
* $response->headers(false);
* // will return
* [
* 'Content-Type: text/plain',
* "Content-Security-Policy: default-src 'self'; style-src 'self' 'unsafe-inline'",
* ]
* ```
*
* @return ResponseHeaders|array<string>
*/
public function headers(bool $raw = false): array
{
if ($raw) {
return $this->headers;
}
$headers = [];
foreach ($this->headers as $header => $header_value) {
if (is_array($header_value)) {
$values = [];
foreach ($header_value as $key => $value) {
$values[] = $key . ' ' . $value;
}
$header_value = implode('; ', $values);
}
$headers[] = "{$header}: {$header_value}";
}
return $headers;
}
/**
* Set a cookie to the response.
*
* Parameters are similar to `setcookie()` PHP function but default options
* are more robust to improve the security.
*
* Default options are:
*
* - expires: 0
* - domain: the value from url_options configuration (unless if it's
* localhost)
* - path: the value from url_options configuration
* - secure: true if url_options protocol is https
* - httponly: true
* - samesite: Strict
*
* Note that `setcookie()` is not called by this method. It must be called
* manually in the `public/index.php` file for instance. Per consequence,
* it doesn't generate a `E_WARNING` error if options are invalid and it
* doesn't return any boolean.
*
* @see https://www.php.net/manual/function.setcookie.php
*
* @param CookieOptions $options
*/
public function setCookie(string $name, string $value, array $options = []): void
{
$url_options = Configuration::$url_options;
$default_options = [
'expires' => 0,
'path' => $url_options['path'],
'secure' => $url_options['protocol'] === 'https',
'httponly' => true,
'samesite' => 'Strict',
];
// Some browsers don't accept cookies if domain is localhost
// @see https://stackoverflow.com/a/1188145
if ($url_options['host'] !== 'localhost') {
$default_options['domain'] = $url_options['host'];
}
$this->cookies[$name] = [
'name' => $name,
'value' => $value,
'options' => array_merge($default_options, $options),
];
}
/**
* Send instructions to the browser to remove a cookie.
*
* To remove the cookie, the expiration date is set to 1 year in the past.
*
* @param CookieOptions $options
*/
public function removeCookie(string $name, array $options = []): void
{
$options['expires'] = Time::ago(1, 'year')->getTimestamp();
$this->setCookie($name, '', $options);
}
/**
* Return the list of cookies.
*
* The cookies are represented as an array with the following keys: name,
* value and options. They can be passed as arguments to the `setcookie()`
* function.
*
* @see https://www.php.net/manual/function.setcookie.php
*
* @return ResponseCookies
*/
public function cookies(): array
{
return $this->cookies;
}
/**
* Generate and return the content of the output, or an empty string if
* no Output is set.
*/
public function render(): string
{
if ($this->output) {
return $this->output->render();
} else {
return '';
}
}
/**
* Send a Response with HTTP headers and cookies.
*
* If the given argument is a Generator, only the first Response headers
* are sent, but all the outputs are echoed in a loop until the Generator
* returns no Response.
*
* You can pass a second argument to not output the response. This is
* useful for HEAD requests. For instance:
*
* $is_head = strtoupper($_SERVER['REQUEST_METHOD']) === 'HEAD';
* \Minz\Response::sendByHttp($response, echo_output: !$is_head);
*
* @param ResponseReturnable $response
*/
public static function sendByHttp(mixed $response, bool $echo_output = true): void
{
if ($response instanceof \Generator) {
$response_generator = $response;
$response = $response_generator->current();
}
http_response_code($response->code());
foreach ($response->cookies() as $cookie) {
setcookie($cookie['name'], $cookie['value'], $cookie['options']);
}
/** @var string[] */
$headers = $response->headers();
foreach ($headers as $header) {
header($header);
}
if (!$echo_output) {
return;
}
if (isset($response_generator)) {
foreach ($response_generator as $response_part) {
/** @var Response */
$response_part = $response_part;
echo $response_part->render();
}
} else {
echo $response->render();
}
}
/**
* Echo a Response to standard output and exit with an error code.
*
* If the Response code is 2xx, the program will exit with code 0.
* Otherwise, it will exit with the corresponding code.
*
* If the given argument is a Generator, only the first Response code is
* considered, but all the outputs are echoed in a loop until the Generator
* returns no Response.
*
* @param ResponseReturnable $response
*/
public static function sendToCli(mixed $response): void
{
if ($response instanceof \Generator) {
$response_generator = $response;
$response = $response_generator->current();
}
$code = $response->code();
if (isset($response_generator)) {
foreach ($response_generator as $response_part) {
/** @var Response */
$response_part = $response_part;
$output = $response_part->render();
if ($output && $output[-1] === "\n") {
echo $output;
} elseif ($output) {
echo $output . "\n";
}
}
} else {
$output = $response->render();
if ($output && $output[-1] === "\n") {
echo $output;
} elseif ($output) {
echo $output . "\n";
}
}
if ($code >= 200 && $code < 300) {
exit(0);
} else {
exit($code);
}
}
}