|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Jvasseur\MailSender; |
| 4 | + |
| 5 | +class MailSender |
| 6 | +{ |
| 7 | + /** |
| 8 | + * @var \Swift_Mailer |
| 9 | + */ |
| 10 | + private $mailer; |
| 11 | + |
| 12 | + /** |
| 13 | + * @var \Twig_Environement |
| 14 | + */ |
| 15 | + private $twig; |
| 16 | + |
| 17 | + public function __construct(\Swift_Mailer $mailer, \Twig_Environement $twig) |
| 18 | + { |
| 19 | + $this->mailer = $mailer; |
| 20 | + $this->twig = $twig; |
| 21 | + } |
| 22 | + |
| 23 | + /** |
| 24 | + * @param string $name |
| 25 | + * @param array $context |
| 26 | + */ |
| 27 | + public function send($name, array $context = []) |
| 28 | + { |
| 29 | + $template = $this->twig->loadTemplate($name); |
| 30 | + |
| 31 | + $blocks = []; |
| 32 | + foreach (['from', 'to', 'subject', 'body_txt', 'body_html'] as $blockName) { |
| 33 | + $rendered = $this->renderBlock($template, $blockName, $context); |
| 34 | + |
| 35 | + if ($rendered) { |
| 36 | + $blocks[$blockName] = $rendered; |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + $blocks = array_merge($context, $blocks); |
| 41 | + |
| 42 | + $mail = new \Swift_Message(); |
| 43 | + $mail->setSubject($blocks['subject']); |
| 44 | + $mail->setFrom($blocks['from']); |
| 45 | + |
| 46 | + if (isset($blocks['to'])) { |
| 47 | + $mail->setTo($blocks['to']); |
| 48 | + } |
| 49 | + |
| 50 | + if (isset($blocks['body_txt'] && $blocks['body_html']) { |
| 51 | + $mail->setBody($block['body_txt']); |
| 52 | + $mail->addPart($block['body_html'], 'text/html'); |
| 53 | + } elseif (isset($blocks['body_txt']) { |
| 54 | + $mail->setBody($block['body_txt']); |
| 55 | + } elseif (isset($blocks['body_html'])) { |
| 56 | + $mail->setBody($block['body_html'], 'text/html'); |
| 57 | + } |
| 58 | + |
| 59 | + $this->mailer->send($mail); |
| 60 | + } |
| 61 | + |
| 62 | + /** |
| 63 | + * Renders a Twig block. |
| 64 | + * |
| 65 | + * see {@link https://github.com/twigphp/Twig/issues/676#issuecomment-15842093} |
| 66 | + * |
| 67 | + * @param \Twig_Template $template |
| 68 | + * @param string $block |
| 69 | + * @param array $context |
| 70 | + * |
| 71 | + * @return string |
| 72 | + * |
| 73 | + * @throws \Exception |
| 74 | + */ |
| 75 | + private function renderBlock(\Twig_Template $template, $block, array $context) |
| 76 | + { |
| 77 | + $context = $template->getEnvironment()->mergeGlobals($context); |
| 78 | + |
| 79 | + $level = ob_get_level(); |
| 80 | + ob_start(); |
| 81 | + try { |
| 82 | + $rendered = $template->renderBlock($block, $context); |
| 83 | + ob_end_clean(); |
| 84 | + |
| 85 | + return $rendered; |
| 86 | + } catch (\Exception $e) { |
| 87 | + while (ob_get_level() > $level) { |
| 88 | + ob_end_clean(); |
| 89 | + } |
| 90 | + |
| 91 | + throw $e; |
| 92 | + } |
| 93 | + } |
| 94 | +} |
0 commit comments