-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathResponse.php
More file actions
executable file
·1058 lines (878 loc) · 29.1 KB
/
Response.php
File metadata and controls
executable file
·1058 lines (878 loc) · 29.1 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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Utopia\Http;
use Utopia\Compression\Compression;
abstract class Response
{
/**
* HTTP content types
*/
public const CONTENT_TYPE_TEXT = 'text/plain';
public const CONTENT_TYPE_HTML = 'text/html';
public const CONTENT_TYPE_JSON = 'application/json';
public const CONTENT_TYPE_XML = 'text/xml';
public const CONTENT_TYPE_JAVASCRIPT = 'text/javascript';
public const CONTENT_TYPE_IMAGE = 'image/*';
public const CONTENT_TYPE_IMAGE_JPEG = 'image/jpeg';
public const CONTENT_TYPE_IMAGE_PNG = 'image/png';
public const CONTENT_TYPE_IMAGE_GIF = 'image/gif';
public const CONTENT_TYPE_IMAGE_SVG = 'image/svg+xml';
public const CONTENT_TYPE_IMAGE_WEBP = 'image/webp';
public const CONTENT_TYPE_IMAGE_ICON = 'image/x-icon';
public const CONTENT_TYPE_IMAGE_BMP = 'image/bmp';
/**
* Chrsets
*/
public const CHARSET_UTF8 = 'UTF-8';
/**
* HTTP response status codes
*/
public const STATUS_CODE_CONTINUE = 100;
public const STATUS_CODE_SWITCHING_PROTOCOLS = 101;
public const STATUS_CODE_PROCESSING = 102;
public const STATUS_CODE_EARLY_HINTS = 103;
public const STATUS_CODE_OK = 200;
public const STATUS_CODE_CREATED = 201;
public const STATUS_CODE_ACCEPTED = 202;
public const STATUS_CODE_NON_AUTHORITATIVE_INFORMATION = 203;
public const STATUS_CODE_NOCONTENT = 204;
public const STATUS_CODE_RESETCONTENT = 205;
public const STATUS_CODE_PARTIALCONTENT = 206;
public const STATUS_CODE_MULTI_STATUS = 207;
public const STATUS_CODE_ALREADY_REPORTED = 208;
public const STATUS_CODE_IM_USED = 226;
public const STATUS_CODE_MULTIPLE_CHOICES = 300;
public const STATUS_CODE_MOVED_PERMANENTLY = 301;
public const STATUS_CODE_FOUND = 302;
public const STATUS_CODE_SEE_OTHER = 303;
public const STATUS_CODE_NOT_MODIFIED = 304;
public const STATUS_CODE_USE_PROXY = 305;
public const STATUS_CODE_UNUSED = 306;
public const STATUS_CODE_TEMPORARY_REDIRECT = 307;
public const STATUS_CODE_PERMANENT_REDIRECT = 308;
public const STATUS_CODE_BAD_REQUEST = 400;
public const STATUS_CODE_UNAUTHORIZED = 401;
public const STATUS_CODE_PAYMENT_REQUIRED = 402;
public const STATUS_CODE_FORBIDDEN = 403;
public const STATUS_CODE_NOT_FOUND = 404;
public const STATUS_CODE_METHOD_NOT_ALLOWED = 405;
public const STATUS_CODE_NOT_ACCEPTABLE = 406;
public const STATUS_CODE_PROXY_AUTHENTICATION_REQUIRED = 407;
public const STATUS_CODE_REQUEST_TIMEOUT = 408;
public const STATUS_CODE_CONFLICT = 409;
public const STATUS_CODE_GONE = 410;
public const STATUS_CODE_LENGTH_REQUIRED = 411;
public const STATUS_CODE_PRECONDITION_FAILED = 412;
public const STATUS_CODE_REQUEST_ENTITY_TOO_LARGE = 413;
public const STATUS_CODE_REQUEST_URI_TOO_LONG = 414;
public const STATUS_CODE_UNSUPPORTED_MEDIA_TYPE = 415;
public const STATUS_CODE_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
public const STATUS_CODE_EXPECTATION_FAILED = 417;
public const STATUS_CODE_IM_A_TEAPOT = 418;
public const STATUS_CODE_MISDIRECTED_REQUEST = 421;
public const STATUS_CODE_UNPROCESSABLE_ENTITY = 422;
public const STATUS_CODE_LOCKED = 423;
public const STATUS_CODE_FAILED_DEPENDENCY = 424;
public const STATUS_CODE_TOO_EARLY = 425;
public const STATUS_CODE_UPGRADE_REQUIRED = 426;
public const STATUS_CODE_PRECONDITION_REQUIRED = 428;
public const STATUS_CODE_TOO_MANY_REQUESTS = 429;
public const STATUS_CODE_REQUEST_HEADER_FIELDS_TOO_LARGE = 431;
public const STATUS_CODE_UNAVAILABLE_FOR_LEGAL_REASONS = 451;
public const STATUS_CODE_INTERNAL_SERVER_ERROR = 500;
public const STATUS_CODE_NOT_IMPLEMENTED = 501;
public const STATUS_CODE_BAD_GATEWAY = 502;
public const STATUS_CODE_SERVICE_UNAVAILABLE = 503;
public const STATUS_CODE_GATEWAY_TIMEOUT = 504;
public const STATUS_CODE_HTTP_VERSION_NOT_SUPPORTED = 505;
public const STATUS_CODE_VARIANT_ALSO_NEGOTIATES = 506;
public const STATUS_CODE_INSUFFICIENT_STORAGE = 507;
public const STATUS_CODE_LOOP_DETECTED = 508;
public const STATUS_CODE_NOT_EXTENDED = 510;
public const STATUS_CODE_NETWORK_AUTHENTICATION_REQUIRED = 511;
/**
* @var array
*/
protected $statusCodes = [
self::STATUS_CODE_CONTINUE => 'Continue',
self::STATUS_CODE_SWITCHING_PROTOCOLS => 'Switching Protocols',
self::STATUS_CODE_PROCESSING => 'Processing',
self::STATUS_CODE_EARLY_HINTS => 'Early Hints',
self::STATUS_CODE_OK => 'OK',
self::STATUS_CODE_CREATED => 'Created',
self::STATUS_CODE_ACCEPTED => 'Accepted',
self::STATUS_CODE_NON_AUTHORITATIVE_INFORMATION => 'Non-Authoritative Information',
self::STATUS_CODE_NOCONTENT => 'No Content',
self::STATUS_CODE_RESETCONTENT => 'Reset Content',
self::STATUS_CODE_PARTIALCONTENT => 'Partial Content',
self::STATUS_CODE_MULTI_STATUS => 'Multi-Status',
self::STATUS_CODE_ALREADY_REPORTED => 'Already Reported',
self::STATUS_CODE_IM_USED => 'IM Used',
self::STATUS_CODE_MULTIPLE_CHOICES => 'Multiple Choices',
self::STATUS_CODE_MOVED_PERMANENTLY => 'Moved Permanently',
self::STATUS_CODE_FOUND => 'Found',
self::STATUS_CODE_SEE_OTHER => 'See Other',
self::STATUS_CODE_NOT_MODIFIED => 'Not Modified',
self::STATUS_CODE_USE_PROXY => 'Use Proxy',
self::STATUS_CODE_UNUSED => '(Unused)',
self::STATUS_CODE_TEMPORARY_REDIRECT => 'Temporary Redirect',
self::STATUS_CODE_PERMANENT_REDIRECT => 'Permanent Redirect',
self::STATUS_CODE_BAD_REQUEST => 'Bad Request',
self::STATUS_CODE_UNAUTHORIZED => 'Unauthorized',
self::STATUS_CODE_PAYMENT_REQUIRED => 'Payment Required',
self::STATUS_CODE_FORBIDDEN => 'Forbidden',
self::STATUS_CODE_NOT_FOUND => 'Not Found',
self::STATUS_CODE_METHOD_NOT_ALLOWED => 'Method Not Allowed',
self::STATUS_CODE_NOT_ACCEPTABLE => 'Not Acceptable',
self::STATUS_CODE_PROXY_AUTHENTICATION_REQUIRED => 'Proxy Authentication Required',
self::STATUS_CODE_REQUEST_TIMEOUT => 'Request Timeout',
self::STATUS_CODE_CONFLICT => 'Conflict',
self::STATUS_CODE_GONE => 'Gone',
self::STATUS_CODE_LENGTH_REQUIRED => 'Length Required',
self::STATUS_CODE_PRECONDITION_FAILED => 'Precondition Failed',
self::STATUS_CODE_REQUEST_ENTITY_TOO_LARGE => 'Request Entity Too Large',
self::STATUS_CODE_REQUEST_URI_TOO_LONG => 'Request-URI Too Long',
self::STATUS_CODE_UNSUPPORTED_MEDIA_TYPE => 'Unsupported Media Type',
self::STATUS_CODE_REQUESTED_RANGE_NOT_SATISFIABLE => 'Requested Range Not Satisfiable',
self::STATUS_CODE_EXPECTATION_FAILED => 'Expectation Failed',
self::STATUS_CODE_IM_A_TEAPOT => 'I\'m a teapot',
self::STATUS_CODE_MISDIRECTED_REQUEST => 'Misdirected Request',
self::STATUS_CODE_UNPROCESSABLE_ENTITY => 'Unprocessable Entity',
self::STATUS_CODE_LOCKED => 'Locked',
self::STATUS_CODE_FAILED_DEPENDENCY => 'Failed Dependency',
self::STATUS_CODE_TOO_EARLY => 'Too Early',
self::STATUS_CODE_UPGRADE_REQUIRED => 'Upgrade Required',
self::STATUS_CODE_PRECONDITION_REQUIRED => 'Precondition Required',
self::STATUS_CODE_TOO_MANY_REQUESTS => 'Too Many Requests',
self::STATUS_CODE_REQUEST_HEADER_FIELDS_TOO_LARGE => 'Request Header Fields Too Large',
self::STATUS_CODE_UNAVAILABLE_FOR_LEGAL_REASONS => 'Unavailable For Legal Reasons',
self::STATUS_CODE_INTERNAL_SERVER_ERROR => 'Internal Server Error',
self::STATUS_CODE_NOT_IMPLEMENTED => 'Not Implemented',
self::STATUS_CODE_BAD_GATEWAY => 'Bad Gateway',
self::STATUS_CODE_SERVICE_UNAVAILABLE => 'Service Unavailable',
self::STATUS_CODE_GATEWAY_TIMEOUT => 'Gateway Timeout',
self::STATUS_CODE_HTTP_VERSION_NOT_SUPPORTED => 'HTTP Version Not Supported',
self::STATUS_CODE_VARIANT_ALSO_NEGOTIATES => 'Variant Also Negotiates',
self::STATUS_CODE_INSUFFICIENT_STORAGE => 'Insufficient Storage',
self::STATUS_CODE_LOOP_DETECTED => 'Loop Detected',
self::STATUS_CODE_NOT_EXTENDED => 'Not Extended',
self::STATUS_CODE_NETWORK_AUTHENTICATION_REQUIRED => 'Network Authentication Required',
];
/**
* Mime Types with compression support
*
* @var array
*/
private static $compressible = [
// Text
'text/html' => true,
'text/richtext' => true,
'text/plain' => true,
'text/css' => true,
'text/x-script' => true,
'text/x-component' => true,
'text/x-java-source' => true,
'text/x-markdown' => true,
// JavaScript
'application/javascript' => true,
'application/x-javascript' => true,
'text/javascript' => true,
'text/js' => true,
// Icons
'image/x-icon' => true,
'image/vnd.microsoft.icon' => true,
// Scripts
'application/x-perl' => true,
'application/x-httpd-cgi' => true,
// XML and JSON
'text/xml' => true,
'application/xml' => true,
'application/rss+xml' => true,
'application/vnd.api+json' => true,
'application/x-protobuf' => true,
'application/json' => true,
'application/manifest+json' => true,
'application/ld+json' => true,
'application/graphql+json' => true,
'application/geo+json' => true,
// Multipart
'multipart/bag' => true,
'multipart/mixed' => true,
// XHTML
'application/xhtml+xml' => true,
// Fonts
'font/ttf' => true,
'font/otf' => true,
'font/x-woff' => true,
'image/svg+xml' => true,
'application/vnd.ms-fontobject' => true,
'application/ttf' => true,
'application/x-ttf' => true,
'application/otf' => true,
'application/x-otf' => true,
'application/truetype' => true,
'application/opentype' => true,
'application/x-opentype' => true,
'application/font-woff' => true,
'application/eot' => true,
'application/font' => true,
'application/font-sfnt' => true,
// WebAssembly
'application/wasm' => true,
'application/javascript-binast' => true,
];
public const COOKIE_SAMESITE_NONE = 'None';
public const COOKIE_SAMESITE_STRICT = 'Strict';
public const COOKIE_SAMESITE_LAX = 'Lax';
public const CHUNK_SIZE = 2000000; //2mb
/**
* @var int
*/
protected int $statusCode = self::STATUS_CODE_OK;
/**
* @var string
*/
protected string $contentType = '';
/**
* @var bool
*/
protected bool $disablePayload = false;
/**
* @var bool
*/
protected bool $sent = false;
/**
* Whether headers have been flushed for a chunked response.
*/
protected bool $chunking = false;
/**
* @var array<string, string|array<string>>
*/
protected array $headers = [];
/**
* @var array
*/
protected array $cookies = [];
/**
* @var float
*/
protected float $startTime = 0;
/**
* @var int
*/
protected int $size = 0;
/**
* @var string
*/
protected string $acceptEncoding = '';
/**
* @var int
*/
protected int $compressionMinSize = Http::COMPRESSION_MIN_SIZE_DEFAULT;
/**
* @var mixed
*/
protected mixed $compressionSupported = [];
/**
* Response constructor.
*
* @param float $time response start time
*/
public function __construct(float $time = 0)
{
$this->startTime = (!empty($time)) ? $time : \microtime(true);
}
private function isCompressible(?string $contentType): bool
{
if (!$contentType) {
return false;
}
// Strip any parameters (e.g. ;charset=utf-8)
$contentType = strtolower(trim(explode(';', $contentType)[0]));
return isset(self::$compressible[$contentType]);
}
/**
* Set content type
*
* Set HTTP content type header.
*
* @param string $type
* @param string $charset
*/
public function setContentType(string $type, string $charset = ''): static
{
$this->contentType = $type.((!empty($charset) ? '; charset='.$charset : ''));
return $this;
}
/**
* Set accept encoding
*
* Set HTTP accept encoding header.
*
* @param string $acceptEncoding
*/
public function setAcceptEncoding(string $acceptEncoding): static
{
$this->acceptEncoding = $acceptEncoding;
return $this;
}
/**
* Set min compression size
*
* Set minimum size for compression to be applied in bytes.
*
* @param int $compressionMinSize
*/
public function setCompressionMinSize(int $compressionMinSize): static
{
$this->compressionMinSize = $compressionMinSize;
return $this;
}
/**
* Set supported compression algorithms
*
* @param mixed $compressionSupported
*/
public function setCompressionSupported(mixed $compressionSupported): static
{
$this->compressionSupported = $compressionSupported;
return $this;
}
/**
* Get content type
*
* Get HTTP content type header.
*
* @return string
*/
public function getContentType(): string
{
return $this->contentType;
}
/**
* Get if response was already sent
*
* @return bool
*/
public function isSent(): bool
{
return $this->sent;
}
/**
* Set status code
*
* Set HTTP response status code between available options. if status code is unknown an exception will be thrown
*
* @param int $code
*
* @throws Exception
*/
public function setStatusCode(int $code = 200): static
{
if (!\array_key_exists($code, $this->statusCodes)) {
throw new Exception('Unknown HTTP status code');
}
$this->statusCode = $code;
return $this;
}
/**
* Get status code
*
* Get HTTP response status code
*
* @return int
**/
public function getStatusCode(): int
{
return $this->statusCode;
}
/**
* Get Response Size
*
* Return output response size in bytes
*
* @return int
*/
public function getSize(): int
{
return $this->size;
}
/**
* Don't allow payload on response output
*/
public function disablePayload(): static
{
$this->disablePayload = true;
return $this;
}
/**
* Allow payload on response output
*/
public function enablePayload(): static
{
$this->disablePayload = false;
return $this;
}
/**
* Add header
*
* Add an HTTP response header
*
* @param string $key
* @param string $value
* @param bool $override
*/
public function addHeader(string $key, string $value, bool $override = true): static
{
if ($override) {
$this->headers[$key] = $value;
return $this;
}
if (\array_key_exists($key, $this->headers)) {
if (\is_array($this->headers[$key])) {
$this->headers[$key][] = $value;
} else {
$this->headers[$key] = [$this->headers[$key], $value];
}
} else {
$this->headers[$key] = $value;
}
return $this;
}
/**
* Remove header
*
* Remove HTTP response header
*
* @param string $key
*/
public function removeHeader(string $key): static
{
if (isset($this->headers[$key])) {
unset($this->headers[$key]);
}
return $this;
}
/**
* Get Headers
*
* Return array of all response headers
*
* @return array<string, array<string, string>>
*/
public function getHeaders(): array
{
return $this->headers;
}
/**
* Add cookie
*
* Add an HTTP cookie to response header
*
* @param string $name
* @param string|null $value
* @param int|null $expire
* @param string|null $path
* @param string|null $domain
* @param bool|null $secure
* @param bool|null $httponly
* @param string|null $sameSite
*/
public function addCookie(string $name, ?string $value = null, ?int $expire = null, ?string $path = null, ?string $domain = null, ?bool $secure = null, ?bool $httponly = null, ?string $sameSite = null): static
{
$name = strtolower($name);
$this->cookies[] = [
'name' => $name,
'value' => $value,
'expire' => $expire,
'path' => $path,
'domain' => $domain,
'secure' => $secure,
'httponly' => $httponly,
'samesite' => $sameSite,
];
return $this;
}
/**
* Remove cookie
*
* Remove HTTP response cookie
*
* @param string $name
*/
public function removeCookie(string $name): static
{
$this->cookies = array_filter($this->cookies, function ($cookie) use ($name) {
return $cookie['name'] !== $name;
});
return $this;
}
/**
* Get Cookies
*
* Return array of all response cookies
*
* @return array
*/
public function getCookies(): array
{
return $this->cookies;
}
/**
* Output response
*
* Generate HTTP response output including the response header (+cookies) and body and prints them.
*
* @param string $body
* @return void
*/
public function send(string $body = ''): void
{
if ($this->sent) {
return;
}
$serverHeader = $this->headers['Server'] ?? 'Utopia/Http';
$this->addHeader('Server', $serverHeader, override: true);
$this->appendCookies();
$hasContentEncoding = false;
foreach ($this->headers as $name => $values) {
if (\strtolower($name) === 'content-encoding') {
$hasContentEncoding = true;
break;
}
}
// Compress body only if all conditions are met:
if (
!$hasContentEncoding &&
!empty($this->acceptEncoding) &&
$this->isCompressible($this->contentType) &&
strlen($body) > $this->compressionMinSize
) {
$algorithm = Compression::fromAcceptEncoding($this->acceptEncoding, $this->compressionSupported);
if ($algorithm) {
$body = $algorithm->compress($body);
$this->addHeader('Content-Length', (string) \strlen($body), override: true);
$this->addHeader('Content-Encoding', $algorithm->getContentEncoding(), override: true);
$this->addHeader('X-Utopia-Compression', 'true', override: true);
$this->addHeader('Vary', 'Accept-Encoding', override: true);
}
}
$this->addHeader('X-Debug-Speed', (string) (microtime(true) - $this->startTime), override: true);
$this->appendHeaders();
// Send response
if ($this->disablePayload) {
$this->end();
return;
}
$headersSize = 0;
foreach ($this->headers as $name => $values) {
if (\is_array($values)) {
foreach ($values as $value) {
$headersSize += \strlen($name . ': ' . $value);
}
$headersSize += (\count($values) - 1) * 2; // linebreaks
} else {
$headersSize += \strlen($name . ': ' . $values);
}
}
$headersSize += (\count($this->headers) - 1) * 2; // linebreaks
$bodyLength = strlen($body);
$this->size += $headersSize + $bodyLength;
if ($bodyLength <= self::CHUNK_SIZE) {
$this->end($body);
} else {
$chunks = str_split($body, self::CHUNK_SIZE);
foreach ($chunks as $chunk) {
$this->write($chunk);
}
$this->end();
}
$this->sent = true;
$this->disablePayload();
}
/**
* Write
*
* Send output
*
* @param string $content
* @return bool False if write cannot complete, such as request ended by client
*/
abstract public function write(string $content): bool;
/**
* End
*
* Send optional content and end
*
* @param string|null $content
* @return void
*/
abstract public function end(?string $content = null): void;
/**
* Output response
*
* Generate HTTP response output including the response header (+cookies) and body and prints them.
*
* @param string $body
* @param bool $end
*
* @return void
*/
public function chunk(string $body = '', bool $end = false): void
{
if ($this->sent) {
return;
}
if ($end) {
$this->sent = true;
}
$this->addHeader('X-Debug-Speed', (string) (microtime(true) - $this->startTime), override: true);
if (!$this->chunking) {
$this->chunking = true;
$this
->appendCookies()
->appendHeaders();
}
if (!$this->disablePayload) {
$this->write($body);
if ($end) {
$this->disablePayload();
$this->end();
}
} else {
$this->end();
}
}
/**
* Stream a large response body with Content-Length.
*
* Sends headers (including Content-Length) then streams the body
* by reading chunks from the provided callback. Adapters may
* override this to use transport-specific optimizations.
*
* @param callable(int, int): string $reader fn($offset, $length) returns chunk data
* @param int $totalSize Total response body size in bytes
*/
public function stream(callable $reader, int $totalSize): void
{
if ($this->sent) {
return;
}
$this->sent = true;
$this->addHeader('Content-Length', (string) $totalSize, override: true);
$this->addHeader('X-Debug-Speed', (string) (microtime(true) - $this->startTime), override: true);
$this->appendCookies()->appendHeaders();
if ($this->disablePayload) {
$this->end();
return;
}
$chunkSize = self::CHUNK_SIZE;
for ($offset = 0; $offset < $totalSize; $offset += $chunkSize) {
$length = \min($chunkSize, $totalSize - $offset);
$data = $reader($offset, $length);
if (!$this->write($data)) {
break;
}
unset($data);
}
$this->end();
$this->disablePayload();
}
/**
* Append headers
*
* Iterating over response headers to generate them using native PHP header function.
* This method is also responsible for generating the response and content type headers.
*/
protected function appendHeaders(): static
{
// Send status code header
$this->sendStatus($this->statusCode);
// Send content type header
if (!empty($this->contentType)) {
$this->addHeader('Content-Type', $this->contentType, override: true);
}
// Set application headers
foreach ($this->headers as $key => $value) {
$this->sendHeader($key, $value);
}
return $this;
}
/**
* Send Status Code
*
* @param int $statusCode
* @return void
*/
abstract protected function sendStatus(int $statusCode): void;
/**
* Send Header
*
* Output Header
*
* @param string $key
* @param string|array<string> $value
* @return void
*/
abstract public function sendHeader(string $key, mixed $value): void;
/**
* Send Cookie
*
* Output Cookie
*
* @param string $name
* @param string $value
* @param array $options
* @return void
*/
abstract protected function sendCookie(string $name, string $value, array $options): void;
/**
* Append cookies
*
* Iterating over response cookies to generate them using native PHP cookie function.
*/
protected function appendCookies(): static
{
foreach ($this->cookies as $cookie) {
$this->sendCookie($cookie['name'], $cookie['value'], [
'expire' => $cookie['expire'],
'path' => $cookie['path'],
'domain' => $cookie['domain'],
'secure' => $cookie['secure'],
'httponly' => $cookie['httponly'],
'samesite' => $cookie['samesite'],
]);
}
return $this;
}
/**
* Redirect
*
* This helper is for sending a 30* HTTP response.
* After setting relevant HTTP headers for redirect response this helper stop application native flow what means the shutdown method will not be executed
*
* NOTICE: it seems webkit based browsers have problems redirecting link with 300 status codes.
*
* @see https://code.google.com/p/chromium/issues/detail?id=75540
* @see https://bugs.webkit.org/show_bug.cgi?id=47425
*
* @param string $url complete absolute URI for redirection as required by the internet standard RFC 2616 (HTTP 1.1)
* @param int $statusCode valid HTTP status code
* @return void
*
* @throws Exception
*
* @see http://tools.ietf.org/html/rfc2616
*/
public function redirect(string $url, int $statusCode = 301): void
{
if (300 == $statusCode) {
\trigger_error('It seems webkit based browsers have problems redirecting link with 300 status codes!', E_USER_NOTICE);
}
$this
->addHeader('Location', $url, override: true)
->setStatusCode($statusCode)
->send('');
}
/**
* HTML
*
* This helper is for sending an HTML HTTP response and sets relevant content type header ('text/html').
*
* @see http://en.wikipedia.org/wiki/JSON
*
* @param string $data
* @return void
*/
public function html(string $data): void
{
$this
->setContentType(self::CONTENT_TYPE_HTML, self::CHARSET_UTF8)
->send($data);
}
/**
* Text
*
* This helper is for sending plain text HTTP response and sets relevant content type header ('text/plain').
*
* @see http://en.wikipedia.org/wiki/JSON
*
* @param string $data
* @return void
*/
public function text(string $data): void
{
$this
->setContentType(self::CONTENT_TYPE_TEXT, self::CHARSET_UTF8)
->send($data);
}
/**
* JSON
*
* This helper is for sending JSON HTTP response.
* It sets relevant content type header ('application/json') and convert a PHP array ($data) to valid JSON using native json_encode
*
* @see http://en.wikipedia.org/wiki/JSON
*
* @param mixed $data
* @return void
*/
public function json($data): void
{
if (!is_array($data) && !$data instanceof \stdClass) {
throw new \Exception('Invalid JSON input var');
}