Advertisement
ArcaniSGK507

Untitled

Mar 27th, 2025
19
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App\Services\Email;
  4.  
  5. use DOMDocument;
  6. use Exception;
  7. use App\Services\Logger;
  8.  
  9. /**
  10. * HTML Validator
  11. *
  12. * Validates and sanitizes HTML content for emails.
  13. *
  14. * @package App\Services\Email
  15. */
  16. class HtmlValidator
  17. {
  18. /**
  19. * @var Logger Logger service
  20. */
  21. private Logger $logger;
  22.  
  23. /**
  24. * HtmlValidator constructor
  25. */
  26. public function __construct()
  27. {
  28. $this->logger = new Logger();
  29. }
  30.  
  31. /**
  32. * Ensure HTML is well-formed before sending
  33. *
  34. * @param string $html The HTML content to validate
  35. * @return string Validated HTML content
  36. */
  37. public function validate(string $html): string
  38. {
  39. try {
  40. // Use DOMDocument for proper HTML validation
  41. $dom = new DOMDocument('1.0', 'UTF-8');
  42.  
  43. // Preserve special characters
  44. $html = htmlspecialchars_decode(htmlentities($html, ENT_QUOTES, 'UTF-8'), ENT_QUOTES);
  45.  
  46. // Suppress libxml errors but store them for inspection
  47. libxml_use_internal_errors(true);
  48.  
  49. // Load HTML into DOMDocument
  50. @$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);
  51.  
  52. // Get validation errors
  53. $errors = libxml_get_errors();
  54. libxml_clear_errors();
  55.  
  56. // Log validation issues but don't break functionality
  57. if (count($errors) > 0) {
  58. $this->logger->warning('HTML validation issues in email', [
  59. 'errors_count' => count($errors)
  60. ]);
  61. }
  62.  
  63. // Return repaired HTML
  64. return $dom->saveHTML($dom->documentElement->lastChild);
  65. } catch (Exception $e) {
  66. // If any error occurs, log it but return the original HTML
  67. $this->logger->error('HTML validation failed: ' . $e->getMessage());
  68. return $html;
  69. }
  70. }
  71. }
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement