Files
blog/app/Http/Response.php
2025-06-20 07:55:37 +00:00

96 lines
2.0 KiB
PHP

<?php
namespace Blog\Http;
/**
* Stellt eine HTTP-Response-Objektklasse bereit.
*
* Kapselt Statuscode, Header, Body und Methoden zum Senden von Antworten.
*/
class Response {
private int $status = 200;
private array $headers = [];
private string $body = "";
/**
* Setzt den HTTP-Statuscode.
*
* @param int $status HTTP-Statuscode
* @return self
*/
public function setStatus(int $status): self {
$this->status = $status;
return $this;
}
/**
* Fügt einen HTTP-Header hinzu.
*
* @param string $key Header-Name
* @param string $val Header-Wert
* @return self
*/
public function addHeader(string $key, string $val): self {
$this->headers[$key] = $val;
return $this;
}
/**
* Gibt das Response-Objekt zurück (für Method Chaining).
*
* @return self
*/
public function getBody(): self {
return $this;
}
/**
* Fügt dem Body Inhalt hinzu.
*
* @param string $content Inhalt, der angehängt wird
* @return self
*/
public function write(string $content): self {
$this->body .= $content;
return $this;
}
/**
* Sendet die HTTP-Antwort an den Client.
*
* @return void
*/
public function send(): void {
http_response_code($this->status);
foreach($this->headers as $key => $val)
header("{$key}: {$val}");
echo $this->body;
}
/**
* Sendet eine JSON-Antwort.
*
* @param array $data Zu sendende Daten
* @param int $status Optionaler HTTP-Statuscode (Standard: 200)
* @return self
*/
public function json(array $data, int $status = 200): self {
$this->setStatus($status);
header("Content-Type: application/json");
$this->body = json_encode($data);
return $this;
}
/**
* Führt eine HTTP-Weiterleitung durch.
*
* @param string $url Ziel-URL
* @param int $status Optionaler Statuscode (Standard: 302)
* @return void
*/
public function redirect(string $url, int $status = 302): void {
http_response_code($status);
header("Location: {$url}");
exit;
}
}