ResponseTrait.php
- Pfad:
src/Framework/Http/ResponseTrait.php - Namespace: Framework\Http
- Zeilen: 69 | Größe: 2,005 Bytes
- Geändert: 2025-12-29 00:18:19 | Gescannt: 2025-12-31 10:22:15
Code Hygiene Score: 100
- Dependencies: 100 (25%)
- LOC: 100 (20%)
- Methods: 100 (20%)
- Secrets: 100 (15%)
- Classes: 100 (10%)
- Magic Numbers: 100 (10%)
Keine Issues gefunden.
Klassen 1
-
ResponseTraittrait Zeile 9
Funktionen 7
-
json()protected Zeile 11 -
jsonError()protected Zeile 18 -
redirect()protected Zeile 23 -
text()Zeile 30 -
html()Zeile 37 -
download()Zeile 44 -
notFound()Zeile 55
Verwendet von 2
- Controller.php trait
- Controller.php use
Code
<?php
declare(strict_types=1);
namespace Framework\Http;
// @responsibility: HTTP-Response-Output für Framework-Layer
trait ResponseTrait
{
protected function json(mixed $data, int $status = 200): void
{
http_response_code($status);
header('Content-Type: application/json');
echo json_encode($data, JSON_UNESCAPED_UNICODE);
}
protected function jsonError(string $message, int $status = 500): void
{
$this->json(['success' => false, 'error' => $message], $status);
}
protected function redirect(string $url, int $status = 302): never
{
http_response_code($status);
header("Location: {$url}");
exit;
}
protected function text(string $content, int $status = 200): void
{
http_response_code($status);
header('Content-Type: text/plain; charset=utf-8');
print $content;
}
protected function html(string $content, int $status = 200): void
{
http_response_code($status);
header('Content-Type: text/html; charset=utf-8');
print $content;
}
protected function download(string $content, string $filename, string $contentType = 'application/octet-stream'): void
{
header('Content-Type: ' . $contentType . '; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Length: ' . strlen($content));
print $content;
}
/**
* Return 404 Not Found response and exit.
*/
protected function notFound(string $message = 'Nicht gefunden'): never
{
$accept = $_SERVER['HTTP_ACCEPT'] ?? '';
$contentType = $_SERVER['CONTENT_TYPE'] ?? '';
$isJson = str_contains($accept, 'application/json') || str_contains($contentType, 'application/json');
if ($isJson) {
$this->json(['error' => $message], 404);
} else {
$this->text("404 - {$message}", 404);
}
exit;
}
}