From 6df3d321d9b67c4541f50158b087d37c4b22e886 Mon Sep 17 00:00:00 2001 From: Daniel Weipert Date: Sun, 12 Nov 2023 11:16:56 +0100 Subject: initial commit --- src/Response.php | 112 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 src/Response.php (limited to 'src/Response.php') 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 @@ +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}"; + } +} -- cgit v1.2.3