summaryrefslogtreecommitdiff
path: root/src/Response.php
blob: 7eab1f5db4dcb65f6e3d51c3459d129ae7bcaa67 (plain)
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
<?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}";
  }
}