Files
laraundfelix/app/Domain/Cms/Widgets/Support/RichText.php
T
LarsandClaude Sonnet 5.5 e904b500fb
CI Feature / test (push) Successful in 7m17s
Deploy Test / test (push) Successful in 6m48s
Deploy Test / deploy (push) Successful in 41s
Setze Symbole vor Absätze, Nummern in Kreise und Symbole statt Aufzählungspunkte im Text (ADR-69)
Zwei Werkzeuge im Texteditor (Symbol vor dem Absatz, Listenstil); gespeichert
werden nur Schlüssel, Bild und Farbe setzt die Ausgabe ein. Kreisfarben aus
der Palette, Verwendung wird mitgezählt.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-30 18:58:10 +01:00

81 lines
2.8 KiB
PHP

<?php
namespace App\Domain\Cms\Widgets\Support;
use Symfony\Component\HtmlSanitizer\HtmlSanitizer;
use Symfony\Component\HtmlSanitizer\HtmlSanitizerConfig;
/**
* Formatierter Text in Widgets: feste Auswahl an Auszeichnungen, kein freies HTML, keine Skripte.
* Bereinigt wird beim Speichern und erneut bei der Darstellung.
*/
final class RichText
{
/** Werkzeugleiste des Editors; muss zur Erlaubnisliste unten passen. */
public const TOOLBAR = [['bold', 'italic', 'link', 'interneSeite'], ['bulletList', 'orderedList'], ['absatzSymbol', 'listenStil'], ['undo', 'redo']];
private static ?HtmlSanitizer $sanitizer = null;
public static function sanitize(?string $html): string
{
if ($html === null || trim($html) === '') {
return '';
}
// Zeichen vor Absätzen und in Listen (ADR-69) bleiben nur mit bekannten Schlüsseln erhalten.
return TextMarkers::clean(trim(self::sanitizer()->sanitize($html)));
}
/**
* Übernimmt Klartext aus dem Altbestand: Absätze an Leerzeilen, Zeichen maskiert.
*/
public static function fromPlainText(?string $text): string
{
$text = trim((string) $text);
if ($text === '') {
return '';
}
$paragraphs = preg_split("/\n\s*\n/", $text) ?: [];
return implode('', array_map(
fn (string $paragraph): string => '<p>'.e(trim($paragraph)).'</p>',
$paragraphs,
));
}
public static function isBlank(?string $html): bool
{
return trim(html_entity_decode(strip_tags((string) $html), ENT_QUOTES | ENT_HTML5, 'UTF-8')) === '';
}
public static function excerpt(?string $html, int $length = 80): string
{
$text = trim(preg_replace('/\s+/u', ' ', html_entity_decode(strip_tags(str_replace('<', ' <', (string) $html)), ENT_QUOTES | ENT_HTML5, 'UTF-8')) ?? '');
return mb_strlen($text) > $length ? rtrim(mb_substr($text, 0, $length - 1)).'…' : $text;
}
private static function sanitizer(): HtmlSanitizer
{
return self::$sanitizer ??= new HtmlSanitizer(
(new HtmlSanitizerConfig)
->allowElement('p', TextMarkers::PARAGRAPH_ATTRIBUTES)
->allowElement('br')
->allowElement('strong')
->allowElement('b')
->allowElement('em')
->allowElement('i')
->allowElement('ul', TextMarkers::LIST_ATTRIBUTES)
->allowElement('ol', TextMarkers::LIST_ATTRIBUTES)
->allowElement('li')
->allowElement('a', ['href'])
->allowLinkSchemes(['http', 'https', 'mailto'])
->allowRelativeLinks()
->forceAttribute('a', 'rel', 'noopener')
->withMaxInputLength(40000),
);
}
}