Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App\Services\Email;
- use Exception;
- /**
- * Email Template Renderer
- *
- * Handles the rendering of email templates with variable substitution.
- *
- * @package App\Services\Email
- */
- class EmailTemplateRenderer
- {
- /**
- * Render an email template with variables
- *
- * @param string $templateName Template name
- * @param array $variables Variables to pass to the template
- * @return string Rendered template
- * @throws Exception If template not found
- */
- public function render(string $templateName, array $variables = []): string
- {
- $templatePath = ROOT_DIR . '/app/Views/emails/' . $templateName . '.php';
- if (!file_exists($templatePath)) {
- throw new Exception("Email template not found: $templateName");
- }
- // Extract variables to make them available in the template
- extract($variables);
- // Start output buffering
- ob_start();
- // Include the template file
- include $templatePath;
- // Get the content and clean the buffer
- return ob_get_clean();
- }
- /**
- * Better HTML to plain text conversion
- *
- * @param string $html HTML content
- * @return string Plain text version
- */
- public function htmlToPlainText(string $html): string
- {
- // Replace common HTML elements with their text equivalents
- $html = preg_replace('/<br\s*\/?>|<\/p>|<\/div>|<\/h[1-6]>/i', "\n", $html);
- $html = preg_replace('/<li\s*>/i', "• ", $html);
- $html = preg_replace('/<\/li>/i', "\n", $html);
- // Strip remaining HTML tags
- $text = strip_tags($html);
- // Decode HTML entities
- $text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
- // Remove extra whitespace
- $text = preg_replace('/\s+/', ' ', $text);
- $text = preg_replace('/\n\s+/', "\n", $text);
- $text = preg_replace('/\n{3,}/', "\n\n", $text);
- return trim($text);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement