ResponseTrait.php

Code Hygiene Score: 100

Keine Issues gefunden.

Klassen 1

Funktionen 7

Verwendet von 2

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;
    }
}
← Übersicht Graph