summaryrefslogtreecommitdiff
path: root/src/Response.php
diff options
context:
space:
mode:
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}";
+ }
+}