ChatMessageFormatter.php
- Pfad:
src/Infrastructure/Formatting/ChatMessageFormatter.php - Namespace: Infrastructure\Formatting
- Zeilen: 88 | Größe: 2,583 Bytes
- Geändert: 2025-12-26 20:06:44 | 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
-
ChatMessageFormatterclass Zeile 9
Funktionen 2
-
formatAnswer()public Zeile 11 -
formatLists()private Zeile 49
Verwendet von 3
- ChatController.php use
- ChatController.php constructor
- ChatServiceProvider.php use
Versionen 2
-
v2
2025-12-26 20:06 | claude-code-hook | modified
Claude Code Pre-Hook Backup vor Edit-Operation -
v1
2025-12-23 08:06 | claude-code-hook | modified
Claude Code Pre-Hook Backup vor Edit-Operation
Code
<?php
declare(strict_types=1);
namespace Infrastructure\Formatting;
// @responsibility: Formatiert Chat-Nachrichten (Markdown → HTML)
class ChatMessageFormatter
{
public function formatAnswer(string $text): string
{
// Remove Ollama/Gemma control tokens
$text = preg_replace('/<\/?end_of_turn>/i', '', $text);
$text = preg_replace('/<\/?start_of_turn>/i', '', $text);
// 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('/^> (.+)$/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);
}
}