HtmxResponseTrait.php

Code Hygiene Score: 100

Keine Issues gefunden.

Klassen 1

Funktionen 5

Verwendet von 2

Code

<?php

declare(strict_types=1);

namespace Framework\Http;

// @responsibility: HTMX-Response-Helpers für HTTP-Layer

trait HtmxResponseTrait
{
    /**
     * Output an HTMX-compatible alert message.
     */
    protected function htmxAlert(string $type, string $message): void
    {
        header('HX-Retarget: #htmx-messages');
        header('HX-Reswap: beforeend');

        $escapedMessage = htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
        $id = 'alert-' . uniqid();
        echo "<div id=\"{$id}\" class=\"alert alert--{$type}\">{$escapedMessage}</div>";
        echo "<script>setTimeout(() => document.getElementById('{$id}')?.remove(), 5000)</script>";
    }

    protected function htmxSuccess(string $message): void
    {
        $this->htmxAlert('success', $message);
    }

    protected function htmxError(string $message): void
    {
        $this->htmxAlert('error', $message);
    }

    protected function isHtmxRequest(): bool
    {
        return isset($_SERVER['HTTP_HX_REQUEST']);
    }

    protected function htmxRedirect(string $url): void
    {
        header('HX-Redirect: ' . $url);
        $this->text('OK');
    }
}
← Übersicht Graph