Advertisement
ArcaniSGK507

Untitled

Mar 27th, 2025
19
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App\Services\Email;
  4.  
  5. use Exception;
  6.  
  7. /**
  8. * Email Template Renderer
  9. *
  10. * Handles the rendering of email templates with variable substitution.
  11. *
  12. * @package App\Services\Email
  13. */
  14. class EmailTemplateRenderer
  15. {
  16. /**
  17. * Render an email template with variables
  18. *
  19. * @param string $templateName Template name
  20. * @param array $variables Variables to pass to the template
  21. * @return string Rendered template
  22. * @throws Exception If template not found
  23. */
  24. public function render(string $templateName, array $variables = []): string
  25. {
  26. $templatePath = ROOT_DIR . '/app/Views/emails/' . $templateName . '.php';
  27.  
  28. if (!file_exists($templatePath)) {
  29. throw new Exception("Email template not found: $templateName");
  30. }
  31.  
  32. // Extract variables to make them available in the template
  33. extract($variables);
  34.  
  35. // Start output buffering
  36. ob_start();
  37.  
  38. // Include the template file
  39. include $templatePath;
  40.  
  41. // Get the content and clean the buffer
  42. return ob_get_clean();
  43. }
  44.  
  45. /**
  46. * Better HTML to plain text conversion
  47. *
  48. * @param string $html HTML content
  49. * @return string Plain text version
  50. */
  51. public function htmlToPlainText(string $html): string
  52. {
  53. // Replace common HTML elements with their text equivalents
  54. $html = preg_replace('/<br\s*\/?>|<\/p>|<\/div>|<\/h[1-6]>/i', "\n", $html);
  55. $html = preg_replace('/<li\s*>/i', "• ", $html);
  56. $html = preg_replace('/<\/li>/i', "\n", $html);
  57.  
  58. // Strip remaining HTML tags
  59. $text = strip_tags($html);
  60.  
  61. // Decode HTML entities
  62. $text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
  63.  
  64. // Remove extra whitespace
  65. $text = preg_replace('/\s+/', ' ', $text);
  66. $text = preg_replace('/\n\s+/', "\n", $text);
  67. $text = preg_replace('/\n{3,}/', "\n\n", $text);
  68.  
  69. return trim($text);
  70. }
  71. }
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement