Files
laraundfelix/app/Domain/Cms/Widgets/Support/RichText.php
T
LarsandClaude Sonnet 5.5 6b43fbb7d1 Verlinke interne Seiten und Sprungmarken auch im formatierten Text der Website
Neues Werkzeug neben dem freien Link in Fließtext, Überschrift-Einleitung und Bild-Text.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 07:03:17 +01:00

80 lines
2.5 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'], ['undo', 'redo']];
private static ?HtmlSanitizer $sanitizer = null;
public static function sanitize(?string $html): string
{
if ($html === null || trim($html) === '') {
return '';
}
return 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')
->allowElement('br')
->allowElement('strong')
->allowElement('b')
->allowElement('em')
->allowElement('i')
->allowElement('ul')
->allowElement('ol')
->allowElement('li')
->allowElement('a', ['href'])
->allowLinkSchemes(['http', 'https', 'mailto'])
->allowRelativeLinks()
->forceAttribute('a', 'rel', 'noopener')
->withMaxInputLength(40000),
);
}
}