Backup #793

ID793
Dateipfad/var/www/dev.campus.systemische-tools.de/src/Infrastructure/Formatting/ChatMessageFormatter.php
Version1
Typ modified
Größe2.3 KB
Hash6231a7868cf71eee38ee69069e779e78603b1ee9300f891caa26eac459dbc37a
Datum2025-12-23 08:06:28
Geändert vonclaude-code-hook
GrundClaude Code Pre-Hook Backup vor Edit-Operation
Datei existiert Ja

Dateiinhalt

<?php

namespace Infrastructure\Formatting;

class ChatMessageFormatter
{
    public function formatAnswer(string $text): string
    {
        // Escape HTML first
        $text = htmlspecialchars($text);

        // Headers
        $text = preg_replace('/^### (.+)$/m', '<h4>$1</h4>', $text);
        $text = preg_replace('/^## (.+)$/m', '<h3>$1</h3>', $text);
        $text = preg_replace('/^# (.+)$/m', '<h3>$1</h3>', $text);

        // Bold
        $text = preg_replace('/\*\*(.+?)\*\*/', '<strong>$1</strong>', $text);

        // Italic
        $text = preg_replace('/\*(.+?)\*/', '<em>$1</em>', $text);

        // Code
        $text = preg_replace('/`(.+?)`/', '<code>$1</code>', $text);

        // Blockquotes
        $text = preg_replace('/^&gt; (.+)$/m', '<blockquote>$1</blockquote>', $text);

        // Lists: Process line by line to correctly wrap consecutive list items
        $text = $this->formatLists($text);

        // Line breaks
        $text = nl2br($text);

        // Clean up multiple <br> tags
        $text = preg_replace('/(<br\s*\/?>\s*){3,}/', '<br><br>', $text);

        return $text;
    }

    private function formatLists(string $text): string
    {
        $lines = explode("\n", $text);
        $result = [];
        $inList = false;

        foreach ($lines as $line) {
            // Check if line is a list item (- or * or numbered)
            if (preg_match('/^[-*] (.+)$/', $line, $matches)) {
                if (!$inList) {
                    $result[] = '<ul>';
                    $inList = true;
                }
                $result[] = '<li>' . $matches[1] . '</li>';
            } elseif (preg_match('/^\d+\. (.+)$/', $line, $matches)) {
                // Numbered list item
                if (!$inList) {
                    $result[] = '<ul>';
                    $inList = true;
                }
                $result[] = '<li>' . $matches[1] . '</li>';
            } else {
                // Not a list item
                if ($inList) {
                    $result[] = '</ul>';
                    $inList = false;
                }
                $result[] = $line;
            }
        }

        // Close any open list
        if ($inList) {
            $result[] = '</ul>';
        }

        return implode("\n", $result);
    }
}

Vollständig herunterladen

Aktionen

Herunterladen

Andere Versionen dieser Datei

ID Version Typ Größe Datum
1549 2 modified 2.3 KB 2025-12-26 20:06
793 1 modified 2.3 KB 2025-12-23 08:06

← Zurück zur Übersicht