<?php
 namespace App\Core\Email; use League\HTMLToMarkdown\HtmlConverter; class HtmlToTextConverter { private const STRIP_BLOCKS_PATTERN = '#<(style|script|head)\b[^>]*>.*?</\1>#is'; public function convert(string $html): string { if (trim($html) === '') { return ''; } $preStripped = preg_replace(self::STRIP_BLOCKS_PATTERN, '', $html) ?? $html; try { $converter = new HtmlConverter([ 'strip_tags' => true, 'remove_nodes' => 'style script head meta title link', 'hard_break' => true, 'use_autolinks' => false, 'suppress_errors' => true, ]); $text = $converter->convert($preStripped); } catch (\Throwable $e) { $text = $this->safeStrip($preStripped); } return $this->normalizeWhitespace($text); } private function safeStrip(string $html): string { $text = strip_tags($html); return html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8'); } private function normalizeWhitespace(string $text): string { $text = str_replace(["\r\n", "\r"], "\n", $text); $text = preg_replace('/[ \t]+\n/', "\n", $text) ?? $text; $text = preg_replace('/\n{3,}/', "\n\n", $text) ?? $text; return trim($text); } } 