Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App\Services\Email;
- use DOMDocument;
- use Exception;
- use App\Services\Logger;
- /**
- * HTML Validator
- *
- * Validates and sanitizes HTML content for emails.
- *
- * @package App\Services\Email
- */
- class HtmlValidator
- {
- /**
- * @var Logger Logger service
- */
- private Logger $logger;
- /**
- * HtmlValidator constructor
- */
- public function __construct()
- {
- $this->logger = new Logger();
- }
- /**
- * Ensure HTML is well-formed before sending
- *
- * @param string $html The HTML content to validate
- * @return string Validated HTML content
- */
- public function validate(string $html): string
- {
- try {
- // Use DOMDocument for proper HTML validation
- $dom = new DOMDocument('1.0', 'UTF-8');
- // Preserve special characters
- $html = htmlspecialchars_decode(htmlentities($html, ENT_QUOTES, 'UTF-8'), ENT_QUOTES);
- // Suppress libxml errors but store them for inspection
- libxml_use_internal_errors(true);
- // Load HTML into DOMDocument
- @$dom->loadHTML('<!DOCTYPE html><html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head><body>' . $html . '</body></html>', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
- // Get validation errors
- $errors = libxml_get_errors();
- libxml_clear_errors();
- // Log validation issues but don't break functionality
- if (count($errors) > 0) {
- $this->logger->warning('HTML validation issues in email', [
- 'errors_count' => count($errors)
- ]);
- }
- // Return repaired HTML
- return $dom->saveHTML($dom->documentElement->lastChild);
- } catch (Exception $e) {
- // If any error occurs, log it but return the original HTML
- $this->logger->error('HTML validation failed: ' . $e->getMessage());
- return $html;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement