From 7472d235bf63562b746f2ca8c9d2822d9dc4dc2a Mon Sep 17 00:00:00 2001 From: Andrea Marco Sartori Date: Tue, 2 Jan 2024 22:36:00 +1000 Subject: [PATCH] Implement the HTTP response value object --- src/ValueObjects/Response.php | 81 +++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 src/ValueObjects/Response.php diff --git a/src/ValueObjects/Response.php b/src/ValueObjects/Response.php new file mode 100644 index 0000000..7d197db --- /dev/null +++ b/src/ValueObjects/Response.php @@ -0,0 +1,81 @@ + $headers + */ + public readonly array $headers; + + /** + * Instantiate the class. + * + * @param array $headers + */ + public function __construct(public readonly string $json, array $headers) + { + $this->headers = $this->normalizeHeaders($headers); + } + + /** + * Normalize the given headers. + * + * @param array $headers + * @return array + */ + private function normalizeHeaders(array $headers): array + { + $normalizedHeaders = []; + + foreach ($headers as $name => $value) { + $normalizedHeaders[strtolower($name)] = $value; + } + + return $normalizedHeaders; + } + + /** + * Retrieve a value from the body or a header. + */ + public function get(string $key): mixed + { + return $this->hasHeader($key) ? $this->header($key) : $this->json($key); + } + + /** + * Determine whether the given header is set. + */ + public function hasHeader(string $header): bool + { + return isset($this->headers[strtolower($header)]); + } + + /** + * Retrieve the given header. + */ + public function header(string $header): ?string + { + return $this->headers[strtolower($header)] ?? null; + } + + /** + * Retrieve a value from the body. + */ + public function json(string $key): mixed + { + $array = JsonParser::parse($this->json)->pointer($key)->toArray(); + + return empty($array) ? null : current($array); + } +}