Files
laraundfelix/app/Domain/Catalog/FormattedText.php
T
LarsandClaude Sonnet 5.5 b942b5331a Biete Überschriften h3 bis h6 an und nimm sie ins Inhaltsverzeichnis auf
Ein Dokument gliedert sich vor allem durch Kapitel der ersten Ebene und
Überschriften im Text. Der Editor bietet h3 bis h6; h1 und h2 aus eingefügtem
Text werden h3. Alle Überschriften des Kapiteltexts stehen automatisch im
Inhaltsverzeichnis der Seite und des PDF (eingerückt, ohne Nummer), mit
Sprungmarken, im PDF mit Seitenzahl, Verweis und verschachtelten Lesezeichen.
Die PDF-Gliederung kennt jetzt bis zu sechs Ebenen und zählt alle Nachkommen.
Unter einem Unterkapitel rücken die Überschriften eine Stufe tiefer (höchstens h6).

Der bestehende Test erwartete h4 für eine Zwischenüberschrift im Kapitel; das gilt
bewusst nicht mehr (h3 bleibt h3 und trägt eine Sprungmarke). Keine Migration,
der Änderungsnachweis bleibt unverändert.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-24 16:23:29 +01:00

729 lines
26 KiB
PHP
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Domain\Catalog;
use Dom\HTMLDocument;
use Dom\Node;
use Symfony\Component\HtmlSanitizer\HtmlSanitizer;
use Symfony\Component\HtmlSanitizer\HtmlSanitizerConfig;
/**
* Formatierter Text in der Verwaltung und im Mitgliederbereich (ADR-50, ADR-51).
*
* Gespeichert wird bereinigtes HTML aus einer festen Auswahl: Absatz, Zwischenüberschriften (h3 bis h6), fett, kursiv, Aufzählung,
* nummerierte Liste, Zitat, Link, Zeilenumbruch, Tabelle und Bild. Alles andere fällt beim Speichern weg, auch Skripte,
* Ereignis­attribute und Links auf andere Schemata als http, https und mailto.
*
* Ein Bild ist nie eine Adresse, sondern ein Verweis auf eine Bildfassung des Medienbestands (`<img data-id="…" alt="…">`).
* Die Adresse entsteht erst bei der Ausgabe, je nach Leser (Verwaltung, Mitglied mit Berechtigung, PDF). Ohne Auflösung
* zeigt die Ausgabe kein Bild.
*
* Klartext aus dem Altbestand bleibt unverändert in der Datenbank. Er wird erst beim Anzeigen oder Bearbeiten in dieselbe
* Form gebracht ({@see self::html()}) und erst beim Speichern als HTML abgelegt. Erkannt wird HTML an einer Regel: Der
* Text beginnt (nach Leerraum) mit einem der Blockelemente dieser Auswahl. Gespeichertes HTML ist kanonisch und beginnt
* deshalb immer so; Klartext beginnt nie mit einem solchen Tag, wenn er nicht von Hand so geschrieben wurde.
*
* Verglichen und gehasht wird immer nur die kanonische Form ({@see self::canonical()}), damit das Öffnen im Editor oder
* eine andere Schreibweise desselben Inhalts keine neue Fassung und keinen Scheinkonflikt erzeugt.
*/
final class FormattedText
{
/** Blockelemente, mit denen gespeichertes HTML beginnt. */
private const BLOCKS = ['p', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'blockquote', 'table', 'img'];
/** Angaben der Redaktion, die formatiert gespeichert werden. Suchbegriffe, Titel und Teaser bleiben Klartext. */
public const FIELDS = ['summary', 'description'];
private static ?HtmlSanitizer $sanitizer = null;
/** Symbolleiste der Editoren; muss zur Auswahl oben passen. */
public const TOOLBAR = [
['bold', 'italic', 'link'],
['h3', 'h4', 'h5', 'h6'],
['bulletList', 'orderedList', 'blockquote'],
['table', 'tableAddRowAfter', 'tableAddColumnAfter', 'tableDeleteRow', 'tableDeleteColumn', 'tableToggleHeaderRow', 'tableDelete'],
['undo', 'redo'],
];
/** Wird der Wert als HTML gelesen (sonst als Klartext des Altbestands)? */
public static function isHtml(?string $value): bool
{
return preg_match('/^\s*<(?:'.implode('|', self::BLOCKS).')[\s>\/]/i', (string) $value) === 1;
}
/**
* Kanonische Form eines gespeicherten oder eingegebenen Werts (HTML oder Klartext). Leer, wenn kein Text übrig ist.
*/
public static function canonical(?string $value): string
{
$value = trim((string) $value);
if ($value === '') {
return '';
}
return self::normalize(self::isHtml($value) ? $value : self::legacyToHtml($value));
}
/**
* Kanonische Form eines Werts, der sicher HTML ist (zum Beispiel aus der Quelle Shinkan), auch wenn er nicht mit
* einem Blockelement beginnt.
*/
public static function canonicalHtml(?string $html): string
{
$html = trim((string) $html);
return $html === '' ? '' : self::normalize($html);
}
/**
* Sicheres HTML zur Ausgabe (für `{!! !!}`); Klartext des Altbestands wird dabei umgewandelt.
*
* Bilder erscheinen nur, wenn `$images` sie auflöst: Die Funktion bekommt die Kennung der Bildfassung und liefert
* `['src' => Adresse, 'alt' => Text]` (Bild), `['note' => Text]` (Hinweis an der Stelle des Bilds) oder null (Bild
* entfällt). Ohne Funktion entfallen alle Bilder; so zeigt keine Ausgabe versehentlich ein Bild ohne Rechteprüfung.
*
* @param (callable(int): ?array{src?: string, alt?: string, note?: string})|null $images
*/
public static function html(?string $value, ?callable $images = null): string
{
return self::renderImages(self::canonical($value), $images);
}
/**
* Sicheres HTML zur Ausgabe an Stellen, die Klartext des Altbestands bisher mit Zeilenumbrüchen zeigten: HTML wird
* bereinigt ausgegeben, Klartext bleibt, wie er war (maskiert, Zeilenumbrüche erhalten).
*
* @param (callable(int): ?array{src?: string, alt?: string, note?: string})|null $images
*/
public static function display(?string $value, ?callable $images = null): string
{
$value = (string) $value;
return self::isHtml($value) ? self::renderImages(self::canonical($value), $images) : nl2br(e($value));
}
/**
* Die Bildfassungen, auf die ein Text verweist, in der Reihenfolge ihres Auftretens (ohne Wiederholung).
*
* @return list<int>
*/
public static function imageIds(?string $value): array
{
$html = self::canonical($value);
if ($html === '' || ! str_contains($html, '<img')) {
return [];
}
$ids = [];
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
foreach ($document->querySelectorAll('img[data-id]') as $image) {
$id = (int) $image->getAttribute('data-id');
if ($id > 0 && ! in_array($id, $ids, true)) {
$ids[] = $id;
}
}
return $ids;
}
/**
* Versieht die Zwischenüberschriften (h3 bis h6, auf oberster Ebene des Texts) mit Sprungmarken `<Präfix>-u<n>` und
* verschiebt ihre Stufe um `$shift` (höchstens h6). Die Marken zählen die nicht leeren Überschriften in ihrer Reihenfolge;
* {@see self::blocks()} zählt dieselben.
*
* @return array{html: string, headings: list<array{level: int, text: string, anchor: string}>}
*/
public static function anchorHeadings(string $html, string $prefix, int $shift = 0): array
{
if (preg_match('/<h[3-6][\s>]/i', $html) !== 1) {
return ['html' => $html, 'headings' => []];
}
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
$headings = [];
foreach (iterator_to_array($document->body->childNodes) as $node) {
if ($node->nodeType !== XML_ELEMENT_NODE || preg_match('/^h([3-6])$/', strtolower($node->nodeName), $match) !== 1) {
continue;
}
$text = trim((string) preg_replace('/\s+/u', ' ', (string) $node->textContent));
if ($text === '') {
continue;
}
$level = min(6, (int) $match[1] + $shift);
$anchor = $prefix.'-u'.(count($headings) + 1);
$replacement = $document->createElement('h'.$level);
$replacement->setAttribute('id', $anchor);
while ($node->firstChild !== null) {
$replacement->appendChild($node->firstChild);
}
$node->replaceWith($replacement);
$headings[] = ['level' => $level, 'text' => $text, 'anchor' => $anchor];
}
return ['html' => trim($document->body->innerHTML), 'headings' => $headings];
}
/**
* Fügt die Adresse an jedes Bild, damit der Editor es zeigt. Die Adresse gehört nicht zum gespeicherten Wert: Die
* Bereinigung entfernt sie beim Übernehmen aus dem Editor wieder.
*
* @param callable(int): ?string $source
*/
public static function forEditor(string $html, callable $source): string
{
if (! str_contains($html, '<img')) {
return $html;
}
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
foreach ($document->querySelectorAll('img[data-id]') as $image) {
$src = $source((int) $image->getAttribute('data-id'));
if ($src !== null) {
$image->setAttribute('src', $src);
}
}
return trim($document->body->innerHTML);
}
/**
* @param (callable(int): ?array{src?: string, alt?: string, note?: string})|null $images
*/
private static function renderImages(string $html, ?callable $images): string
{
if ($html === '' || ! str_contains($html, '<img')) {
return $html;
}
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
foreach (iterator_to_array($document->querySelectorAll('img')) as $image) {
$found = $images === null ? null : $images((int) $image->getAttribute('data-id'));
if (isset($found['src'])) {
$image->removeAttribute('data-id');
$image->setAttribute('src', (string) $found['src']);
$image->setAttribute('alt', (string) ($found['alt'] ?? $image->getAttribute('alt')));
$image->setAttribute('loading', 'lazy');
continue;
}
if (isset($found['note'])) {
$note = $document->createElement('p');
$note->setAttribute('class', 'mb-bildhinweis');
$note->textContent = (string) $found['note'];
$image->replaceWith($note);
continue;
}
$image->remove();
}
return trim($document->body->innerHTML);
}
public static function isBlank(?string $value): bool
{
return self::canonical($value) === '';
}
/** Sind beide Werte inhaltlich gleich (unabhängig von Klartext oder Schreibweise des HTML)? */
public static function same(?string $a, ?string $b): bool
{
return self::canonical($a) === self::canonical($b);
}
/**
* Text ohne Auszeichnung für Orte, die kein HTML vertragen (Zahlungsdienst, Meta-Beschreibung, Listen). Absätze sind
* durch Leerzeilen getrennt, Listenpunkte beginnen mit „- “ beziehungsweise „1. “.
*/
public static function plain(?string $value): string
{
$out = [];
foreach (self::blocks($value) as $block) {
$text = self::plainBlock($block);
if ($text !== '') {
$out[] = $text;
}
}
return trim(implode("\n\n", $out));
}
/**
* @param array<string, mixed> $block
*/
private static function plainBlock(array $block): string
{
return match ($block['type']) {
'bullets' => implode("\n", array_map(fn (array $item): string => '- '.self::runsText($item), $block['items'])),
'numbered' => implode("\n", array_map(fn (array $item, int $n): string => ($n + 1).'. '.self::runsText($item), $block['items'], array_keys($block['items']))),
'table' => implode("\n", array_map(
fn (array $row): string => implode(' | ', array_map(
fn (array $cell): string => trim((string) preg_replace('/\s+/u', ' ', implode(' ', array_filter(array_map(fn (array $inner): string => self::plainBlock($inner), $cell['blocks']))))),
$row,
)),
$block['rows'],
)),
// Ein Bild hat im Klartext keinen Platz (Listen, Auszüge, Meta-Beschreibung).
'image' => '',
default => self::runsText($block['runs']),
};
}
/** Kurzer Text für Listen und Karten. */
public static function excerpt(?string $value, int $length = 120): string
{
$text = trim((string) preg_replace('/\s+/u', ' ', self::plain($value)));
return mb_strlen($text) > $length ? rtrim(mb_substr($text, 0, $length - 1)).'…' : $text;
}
/**
* Zerlegung in Blöcke mit Textabschnitten für das PDF. Ein Textabschnitt (Run) trägt `text`, `bold`, `italic` und
* `href`. Eine Tabelle besteht aus Zeilen mit Zellen (`header`, `colspan`, `rowspan`, `blocks`); ein Bild trägt die
* Kennung seiner Bildfassung (`id`) und den Alternativtext.
*
* @return list<array<string, mixed>>
*/
public static function blocks(?string $value): array
{
$html = self::canonical($value);
if ($html === '') {
return [];
}
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
return self::extractBlocks($document->body);
}
/**
* @return list<array<string, mixed>>
*/
private static function extractBlocks(Node $parent): array
{
$blocks = [];
foreach ($parent->childNodes as $node) {
if ($node->nodeType !== XML_ELEMENT_NODE) {
continue;
}
$name = strtolower($node->nodeName);
if (in_array($name, ['ul', 'ol'], true)) {
$items = [];
foreach ($node->childNodes as $item) {
if ($item->nodeType === XML_ELEMENT_NODE && strtolower($item->nodeName) === 'li') {
$items[] = self::runs($item);
}
}
$blocks[] = ['type' => $name === 'ul' ? 'bullets' : 'numbered', 'items' => $items];
continue;
}
if ($name === 'img') {
$blocks[] = ['type' => 'image', 'id' => (int) $node->getAttribute('data-id'), 'alt' => (string) $node->getAttribute('alt')];
continue;
}
if ($name === 'table') {
$rows = [];
foreach ($node->querySelectorAll('tr') as $row) {
$cells = [];
foreach ($row->childNodes as $cell) {
if ($cell->nodeType !== XML_ELEMENT_NODE || ! in_array(strtolower($cell->nodeName), ['th', 'td'], true)) {
continue;
}
$cells[] = [
'header' => strtolower($cell->nodeName) === 'th',
'colspan' => max(1, (int) $cell->getAttribute('colspan')),
'rowspan' => max(1, (int) $cell->getAttribute('rowspan')),
'blocks' => self::extractBlocks($cell),
];
}
if ($cells !== []) {
$rows[] = $cells;
}
}
$blocks[] = ['type' => 'table', 'rows' => $rows];
continue;
}
$level = preg_match('/^h([3-6])$/', $name, $heading) === 1 ? (int) $heading[1] : 0;
$type = match (true) {
$level > 0 => 'heading',
$name === 'blockquote' => 'quote',
default => 'paragraph',
};
// Ein Bild mitten im Absatz (so setzt der Editor es) teilt den Absatz: Text davor, Bild, Text danach.
$images = $node->querySelectorAll('img');
if (count($images) === 0) {
$blocks[] = self::textBlock($type, $level, self::runs($node));
continue;
}
$pending = [];
foreach ($node->childNodes as $child) {
if ($child->nodeType === XML_ELEMENT_NODE && strtolower($child->nodeName) === 'img') {
if (trim(self::runsText($pending)) !== '') {
$blocks[] = self::textBlock($type, $level, $pending);
}
$pending = [];
$blocks[] = ['type' => 'image', 'id' => (int) $child->getAttribute('data-id'), 'alt' => (string) $child->getAttribute('alt')];
continue;
}
$holder = $node->ownerDocument->createElement('span');
$holder->appendChild($child->cloneNode(true));
$pending = [...$pending, ...self::runs($holder)];
}
if (trim(self::runsText($pending)) !== '') {
$blocks[] = self::textBlock($type, $level, $pending);
}
}
return $blocks;
}
/**
* Ein Textblock; eine Überschrift trägt zusätzlich ihre Stufe (3 bis 6) und ihren Text ohne Auszeichnung.
*
* @param list<array{text: string, bold: bool, italic: bool, href: ?string}> $runs
* @return array<string, mixed>
*/
private static function textBlock(string $type, int $level, array $runs): array
{
return $type === 'heading'
? ['type' => $type, 'level' => $level, 'text' => self::runsText($runs), 'runs' => $runs]
: ['type' => $type, 'runs' => $runs];
}
/**
* Klartext des Altbestands als HTML: Absätze an Leerzeilen, Listen mit „- “, „• “ oder „1. “, Zwischenüberschriften
* mit „## “. Dieselben Konventionen wie {@see GuideText}.
*/
public static function legacyToHtml(?string $text): string
{
$html = '';
foreach (GuideText::blocks($text) as $block) {
$html .= match ($block['type']) {
'heading' => '<h3>'.e($block['text']).'</h3>',
'bullets' => '<ul>'.implode('', array_map(fn (string $item): string => '<li><p>'.e($item).'</p></li>', $block['items'])).'</ul>',
'numbered' => '<ol>'.implode('', array_map(fn (string $item): string => '<li><p>'.e($item).'</p></li>', $block['items'])).'</ol>',
default => '<p>'.e($block['text']).'</p>',
};
}
return $html;
}
private static function normalize(string $html): string
{
$html = self::mapLegacyTags($html);
$html = trim(self::sanitizer()->sanitize($html));
if ($html === '') {
return '';
}
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
$body = $document->body;
// Ein Bild steht zwischen den Absätzen, in einem Absatz (so setzt der Editor es) oder in einer Tabellenzelle und braucht
// seine Bildfassung. Anderswo (Liste, Zitat, Überschrift) entfällt es.
foreach (iterator_to_array($document->querySelectorAll('img')) as $image) {
if (! self::mayHoldImage($image->parentNode, $body) || (int) $image->getAttribute('data-id') < 1) {
$image->remove();
}
}
$out = '';
$loose = '';
$flush = function () use (&$out, &$loose): void {
$loose = trim($loose);
if ($loose !== '' && trim(strip_tags(str_replace(['<br>', '<br/>', '<br />'], '', $loose))) !== '') {
$out .= '<p>'.$loose.'</p>';
}
$loose = '';
};
foreach ($body->childNodes as $node) {
if ($node->nodeType === XML_ELEMENT_NODE && in_array(strtolower($node->nodeName), self::BLOCKS, true)) {
$flush();
$out .= self::block($node);
continue;
}
$loose .= $document->saveHtml($node);
}
$flush();
return self::hasText($out) || str_contains($out, '<img') ? $out : '';
}
/** Ein Blockelement ohne Leerraum zwischen den Kindern; Listenpunkte tragen ihren Text immer in einem Absatz. */
private static function block(Node $node): string
{
$name = strtolower($node->nodeName);
if ($name === 'img') {
$id = (int) $node->getAttribute('data-id');
return $id > 0 ? '<img data-id="'.$id.'" alt="'.e(trim((string) $node->getAttribute('alt'))).'">' : '';
}
if ($name === 'table') {
return self::table($node);
}
if (in_array($name, ['ul', 'ol'], true)) {
$items = '';
foreach ($node->childNodes as $child) {
if ($child->nodeType !== XML_ELEMENT_NODE || strtolower($child->nodeName) !== 'li') {
continue;
}
$inner = self::inner($child);
if (! str_contains($inner, '<p>')) {
$inner = '<p>'.$inner.'</p>';
}
if (self::hasText($inner)) {
$items .= '<li>'.$inner.'</li>';
}
}
return $items === '' ? '' : '<'.$name.'>'.$items.'</'.$name.'>';
}
$inner = self::inner($node);
if ($name === 'blockquote' && ! str_contains($inner, '<p>')) {
$inner = '<p>'.$inner.'</p>';
}
return self::hasContent($inner) ? '<'.$name.'>'.$inner.'</'.$name.'>' : '';
}
/**
* Eine Tabelle in der festen Form des Editors: Zeilen mit Kopf- (`th`) und Datenzellen (`td`), Zellen mit Absätzen,
* Verbindungen nur als `colspan` und `rowspan` über 1. Breiten, Gestaltung und Zwischenebenen entfallen.
*/
private static function table(Node $table): string
{
$rows = '';
foreach ($table->querySelectorAll('tr') as $row) {
$cells = '';
foreach ($row->childNodes as $cell) {
if ($cell->nodeType !== XML_ELEMENT_NODE || ! in_array(strtolower($cell->nodeName), ['th', 'td'], true)) {
continue;
}
$name = strtolower($cell->nodeName);
$attributes = '';
foreach (['colspan', 'rowspan'] as $span) {
$value = (int) $cell->getAttribute($span);
if ($value > 1) {
$attributes .= ' '.$span.'="'.min($value, 50).'"';
}
}
$inner = self::inner($cell);
$cells .= '<'.$name.$attributes.'>'.($inner === '' ? '<p></p>' : (preg_match('/^<(?:p|ul|ol|blockquote|h[3-6]|img)[\s>]/', $inner) === 1 ? $inner : '<p>'.$inner.'</p>')).'</'.$name.'>';
}
if ($cells !== '') {
$rows .= '<tr>'.$cells.'</tr>';
}
}
return $rows !== '' && (self::hasText($rows) || str_contains($rows, '<img')) ? '<table><tbody>'.$rows.'</tbody></table>' : '';
}
private static function inner(Node $node): string
{
$html = '';
foreach ($node->childNodes as $child) {
if ($child->nodeType === XML_ELEMENT_NODE && in_array(strtolower($child->nodeName), ['ul', 'ol', 'p', 'blockquote', 'img'], true)) {
$html .= self::block($child);
continue;
}
$html .= $node->ownerDocument->saveHtml($child);
}
return trim($html);
}
/** Wo darf ein Bild stehen: im Text, in einer Tabellenzelle oder in einem Absatz dort. */
private static function mayHoldImage(?Node $parent, Node $body): bool
{
if ($parent === null) {
return false;
}
$name = strtolower($parent->nodeName);
if ($parent === $body || in_array($name, ['td', 'th'], true)) {
return true;
}
return $name === 'p' && $parent->parentNode !== null && ($parent->parentNode === $body || in_array(strtolower($parent->parentNode->nodeName), ['td', 'th'], true));
}
/** Hat der Ausschnitt einen Inhalt: Text oder ein Bild? */
private static function hasContent(string $html): bool
{
return self::hasText($html) || str_contains($html, '<img');
}
private static function hasText(string $html): bool
{
return trim(html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8')) !== '';
}
/** b, i und die Überschriftsstufen 1 und 2 der Quelle werden auf die feste Auswahl abgebildet (h1 und h2 gehören dem Dokument und dem Kapitel); der Rest fällt in der Bereinigung weg. */
private static function mapLegacyTags(string $html): string
{
$html = (string) preg_replace('/<(\/?)b(?=[\s>\/])/i', '<$1strong', $html);
$html = (string) preg_replace('/<(\/?)i(?=[\s>\/])/i', '<$1em', $html);
$html = (string) preg_replace('/<(\/?)h[12](?=[\s>\/])/i', '<$1h3', $html);
return (string) preg_replace('/<(\/?)div(?=[\s>\/])/i', '<$1p', $html);
}
/**
* @return list<array{text: string, bold: bool, italic: bool, href: ?string}>
*/
private static function runs(Node $node, bool $bold = false, bool $italic = false, ?string $href = null): array
{
$runs = [];
foreach ($node->childNodes as $child) {
if ($child->nodeType === XML_TEXT_NODE) {
$runs[] = ['text' => (string) $child->textContent, 'bold' => $bold, 'italic' => $italic, 'href' => $href];
continue;
}
if ($child->nodeType !== XML_ELEMENT_NODE) {
continue;
}
$name = strtolower($child->nodeName);
if ($name === 'br') {
$runs[] = ['text' => "\n", 'bold' => $bold, 'italic' => $italic, 'href' => $href];
continue;
}
if (in_array($name, ['p', 'ul', 'ol', 'blockquote'], true)) {
// Verschachtelte Blöcke (Absatz im Listenpunkt) werden zu Fließtext.
$runs = [...$runs, ...self::runs($child, $bold, $italic, $href)];
continue;
}
$runs = [...$runs, ...self::runs(
$child,
$bold || $name === 'strong',
$italic || $name === 'em',
$name === 'a' ? ((string) $child->getAttribute('href') ?: $href) : $href,
)];
}
return $runs;
}
/**
* @param list<array{text: string, bold: bool, italic: bool, href: ?string}> $runs
*/
private static function runsText(array $runs): string
{
return trim(implode('', array_map(fn (array $run): string => $run['text'], $runs)));
}
private static function sanitizer(): HtmlSanitizer
{
return self::$sanitizer ??= new HtmlSanitizer(
(new HtmlSanitizerConfig)
->allowElement('p')
->allowElement('br')
->allowElement('h3')
->allowElement('h4')
->allowElement('h5')
->allowElement('h6')
->allowElement('strong')
->allowElement('em')
->allowElement('ul')
->allowElement('ol')
->allowElement('li')
->allowElement('blockquote')
->allowElement('table')
->allowElement('thead')
->allowElement('tbody')
->allowElement('tfoot')
->allowElement('tr')
->allowElement('th', ['colspan', 'rowspan'])
->allowElement('td', ['colspan', 'rowspan'])
->allowElement('img', ['data-id', 'alt'])
->allowElement('a', ['href'])
->allowLinkSchemes(['http', 'https', 'mailto'])
->allowRelativeLinks(false)
->forceAttribute('a', 'rel', 'noopener noreferrer')
->withMaxInputLength(100000),
);
}
}