Skip to content
This repository has been archived by the owner on Mar 24, 2021. It is now read-only.

Commit

Permalink
First version
Browse files Browse the repository at this point in the history
  • Loading branch information
jvasseur committed Aug 27, 2015
0 parents commit 87e211a
Show file tree
Hide file tree
Showing 3 changed files with 116 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/composer.lock
/vendor/
20 changes: 20 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "jvasseur/mail-sender",
"description": "Send mails with Swiftmailer and Twig",
"type": "library",
"license": "MIT",
"authors": [
{
"name": "Jérôme Vasseur",
"email": "jerome.vasseur@jhome.fr"
}
],
"autoload": {
"psr-4": {
"Jvasseur\\MailSender\\": "src/"
}
},
"require": {
"php": ">=5.4"
}
}
94 changes: 94 additions & 0 deletions src/MailSender.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
<?php

namespace Jvasseur\MailSender;

class MailSender
{
/**
* @var \Swift_Mailer
*/
private $mailer;

/**
* @var \Twig_Environement
*/
private $twig;

public function __construct(\Swift_Mailer $mailer, \Twig_Environement $twig)
{
$this->mailer = $mailer;
$this->twig = $twig;
}

/**
* @param string $name
* @param array $context
*/
public function send($name, array $context = [])
{
$template = $this->twig->loadTemplate($name);

$blocks = [];
foreach (['from', 'to', 'subject', 'body_txt', 'body_html'] as $blockName) {
$rendered = $this->renderBlock($template, $blockName, $context);

if ($rendered) {
$blocks[$blockName] = $rendered;
}
}

$blocks = array_merge($context, $blocks);

$mail = new \Swift_Message();
$mail->setSubject($blocks['subject']);
$mail->setFrom($blocks['from']);

if (isset($blocks['to'])) {
$mail->setTo($blocks['to']);
}

if (isset($blocks['body_txt'] && $blocks['body_html']) {
$mail->setBody($block['body_txt']);
$mail->addPart($block['body_html'], 'text/html');
} elseif (isset($blocks['body_txt']) {
$mail->setBody($block['body_txt']);
} elseif (isset($blocks['body_html'])) {
$mail->setBody($block['body_html'], 'text/html');
}

$this->mailer->send($mail);
}

/**
* Renders a Twig block.
*
* see {@link https://github.com/twigphp/Twig/issues/676#issuecomment-15842093}
*
* @param \Twig_Template $template
* @param string $block
* @param array $context
*
* @return string
*
* @throws \Exception
*/
private function renderBlock(\Twig_Template $template, $block, array $context)
{
$context = $template->getEnvironment()->mergeGlobals($context);

$level = ob_get_level();
ob_start();
try {
$rendered = $template->renderBlock($block, $context);
ob_end_clean();

return $rendered;
} catch (\Exception $e) {
while (ob_get_level() > $level) {
ob_end_clean();
}

throw $e;
}
}
}

0 comments on commit 87e211a

Please sign in to comment.