summaryrefslogtreecommitdiff
path: root/src/Response.php
diff options
context:
space:
mode:
authorDaniel Weipert <code@drogueronin.de>2023-11-12 11:16:56 +0100
committerDaniel Weipert <code@drogueronin.de>2023-11-20 17:30:04 +0100
commit6df3d321d9b67c4541f50158b087d37c4b22e886 (patch)
tree06031988bb4b957b76f051af366ced448a48545f /src/Response.php
initial commit
Diffstat (limited to 'src/Response.php')
-rw-r--r--src/Response.php112
1 files changed, 112 insertions, 0 deletions
diff --git a/src/Response.php b/src/Response.php
new file mode 100644
index 0000000..7eab1f5
--- /dev/null
+++ b/src/Response.php
@@ -0,0 +1,112 @@
+<?php
+
+namespace GeminiFoundation;
+
+class Response
+{
+ protected Status $statusCode;
+ protected string $meta;
+ protected string $body;
+
+ /**
+ * @param Status $statusCode
+ * @param string $meta
+ * @param string $body
+ */
+ public function __construct(
+ $statusCode = Status::SUCCESS,
+ $meta = '',
+ $body = ''
+ )
+ {
+ $this->statusCode = $statusCode;
+ $this->meta = $meta;
+ $this->body = $body;
+ }
+
+ public static function fromString(string $string): static
+ {
+ $parts = explode("\r\n", $string);
+ $header = $parts[0];
+ $headerParts = explode(' ', $header);
+ $statusCode = Status::from(intval($headerParts[0]));
+ $meta = implode(' ', array_slice($headerParts, 1));
+ $body = implode("\r\n", array_slice($parts, 1));
+
+ return new self($statusCode, $meta, $body);
+ }
+
+ public function setStatusCode(Status|int $statusCode): static
+ {
+ $this->statusCode = $statusCode;
+
+ return $this;
+ }
+
+ public function getStatusCode(): Status|int
+ {
+ return $this->statusCode;
+ }
+
+ public function setMeta(string $meta): static
+ {
+ $this->meta = $meta;
+
+ return $this;
+ }
+
+ public function getMeta(): string
+ {
+ return $this->meta;
+ }
+
+ public function setBody(string $body): static
+ {
+ $this->body = $body;
+
+ return $this;
+ }
+
+ public function getBody(): string
+ {
+ return $this->body;
+ }
+
+ public function append(string $string): static
+ {
+ $this->body .= $string;
+
+ return $this;
+ }
+
+ public function getHeader(): string
+ {
+ return "{$this->statusCode->value} {$this->meta}\r\n";
+ }
+
+ public function prepareResponse(): static
+ {
+ if ($this->statusCode == Status::SUCCESS) {
+ if (empty($this->meta)) {
+ $this->meta = 'text/gemini; charset=utf-8';
+ }
+ }
+
+ return $this;
+ }
+
+ /**
+ * @param resource $connection
+ */
+ public function send($connection): int
+ {
+ return fwrite($connection, $this);
+ }
+
+ public function __toString(): string
+ {
+ $this->prepareResponse();
+
+ return "{$this->getHeader()}{$this->body}";
+ }
+}