summaryrefslogtreecommitdiff
path: root/src/Response.php
diff options
context:
space:
mode:
authorDavid T. Sadler <davidtsadler@googlemail.com>2026-08-09 20:04:39 +0100
committerDavid T. Sadler <davidtsadler@googlemail.com>2026-08-09 20:04:39 +0100
commitb9c4f1dcf1333c14e2d1b67561ec7a5f955baa6e (patch)
tree610536953be739d0778f19c90c477f080a24718a /src/Response.php
Initial commitHEADmain
Diffstat (limited to 'src/Response.php')
-rw-r--r--src/Response.php50
1 files changed, 50 insertions, 0 deletions
diff --git a/src/Response.php b/src/Response.php
new file mode 100644
index 0000000..d3c4f69
--- /dev/null
+++ b/src/Response.php
@@ -0,0 +1,50 @@
+<?php
+
+declare(strict_types=1);
+
+namespace TCB;
+
+final class Response
+{
+ /**
+ * @param array<string, string> $headers Key-value pairs of additional HTTP headers
+ */
+ public function __construct(
+ public readonly int $statusCode,
+ public readonly string $contentType,
+ public readonly string $body,
+ public readonly array $headers = [],
+ ) {}
+
+ public function __toString(): string
+ {
+ $reason = match ($this->statusCode) {
+ 200 => 'OK',
+ 400 => 'Bad Request',
+ 401 => 'Unauthorized',
+ 403 => 'Forbidden',
+ 404 => 'Not Found',
+ 405 => 'Method Not Allowed',
+ 500 => 'Internal Server Error',
+ default => '',
+ };
+
+ $statusLine = trim("HTTP/1.1 {$this->statusCode} {$reason}");
+ $contentLength = strlen($this->body);
+
+ // Build base headers.
+ $formattedHeaders = [
+ $statusLine,
+ "Content-Type: $this->contentType",
+ "Content-Length: $contentLength",
+ "Connection: close",
+ ];
+
+ // Format and append custom headers.
+ foreach ($this->headers as $name => $value) {
+ $formattedHeaders[] = "$name: $value";
+ }
+
+ return implode("\r\n", $formattedHeaders) . "\r\n\r\n" . $this->body;
+ }
+}