Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
lemoinem committed Mar 21, 2016
0 parents commit 48122f1
Show file tree
Hide file tree
Showing 9 changed files with 466 additions and 0 deletions.
17 changes: 17 additions & 0 deletions DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

namespace WMC\SwiftmailerTwigBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class Configuration implements ConfigurationInterface
{
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('wmc_swiftmailer_twig');

return $treeBuilder;
}
}
31 changes: 31 additions & 0 deletions DependencyInjection/WMCSwiftmailerTwigExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace WMC\SwiftmailerTwigBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;

class WMCSwiftmailerTwigExtension extends Extension implements CompilerPassInterface
{
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.xml');
}

/**
* {@inheritDoc}
*/
public function process(ContainerBuilder $container)
{
if (!$container->hasExtension('fos_user')) {
$container->removeDefinition('wmc.swiftmailer_twig.fosub');
}
}
}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2016 WeMakeCustom

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
63 changes: 63 additions & 0 deletions Mailer/FOSUserMailer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?php

namespace WMC\SwiftmailerTwigBundle\Mailer;

use FOS\UserBundle\Mailer\MailerInterface;
use FOS\UserBundle\Model\UserInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

use Swift_Mailer;
use Swift_Message;

class FOSUserMailer implements MailerInterface
{
protected $mailer;
protected $router;
protected $helper;
protected $parameters;

public function __construct(Swift_Mailer $mailer, UrlGeneratorInterface $router, TwigSwiftHelper $helper, array $parameters)
{
$this->mailer = $mailer;
$this->router = $router;
$this->helper = $helper;
$this->parameters = $parameters;
}

public function sendConfirmationEmailMessage(UserInterface $user)
{
$template = $this->parameters['template']['confirmation'];
$url = $this->router->generate('fos_user_registration_confirm', array('token' => $user->getConfirmationToken()), true);
$context = array(
'user' => $user,
'confirmationUrl' => $url
);

$this->sendMessage($template, $context, $this->parameters['from_email']['confirmation'], $user->getEmail());
}

public function sendResettingEmailMessage(UserInterface $user)
{
$template = $this->parameters['template']['resetting'];
$url = $this->router->generate('fos_user_resetting_reset', array('token' => $user->getConfirmationToken()), true);
$context = array(
'user' => $user,
'confirmationUrl' => $url
);
$this->sendMessage($template, $context, $this->parameters['from_email']['resetting'], $user->getEmail());
}

/**
* @param string $templateName
* @param array $context
*/
protected function sendMessage($templateName, $context, $fromEmail, $toEmail)
{
$message = Swift_Message::newInstance()
->setFrom($fromEmail)
->setTo($toEmail);

$this->helper->populateMessage($message, $templateName, $context);
$this->mailer->send($message);
}
}
112 changes: 112 additions & 0 deletions Mailer/TwigSwiftHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
<?php

namespace WMC\SwiftmailerTwigBundle\Mailer;

use Swift_Mailer;
use Swift_Message;
use Swift_Image;
use Symfony\Component\DomCrawler\Crawler;
use Twig_Environment;

/**
* Inspired from FOS User Bundle
* @link https://github.com/FriendsOfSymfony/FOSUserBundle/blob/90cb9c1785f7a7c406dddc5295b41e85b6c65905/Mailer/TwigSwiftMailer.php
*/
class TwigSwiftHelper
{
/**
* @var Twig_Environment
*/
protected $twig;

/**
* Used to resolve inline images
* @var string absolute path to Web root
*/
protected $web_directory;

public function __construct(Twig_Environment $twig, $web_directory)
{
$this->twig = $twig;
$this->web_directory = $web_directory;
}

protected function extractMessageContent($template_name, $context, $parts = array('subject', 'content' => 'body_text'))
{
$template = $this->twig->loadTemplate($template_name);
$context = $this->twig->mergeGlobals($context);

$data = array();

foreach ($parts as $k => $part) {
$key = is_numeric($k) ? $part : $k;
$data[$key] = $template->renderBlock($part, $context);
}

return $data;
}

/**
* Replace all src of img.inline-image with an embedded image
*
* @param Swift_Message $message
*/
protected function inlineImages(Swift_Message $message)
{
$html = $message->getBody();

$crawler = new Crawler();
$crawler->addHtmlContent($html);

$imgs = array();
$replaces = array();

foreach ($crawler->filterXPath("//img[contains(concat(' ',normalize-space(@class), ' '), ' inline-image ')]") as $img) {
$normalized_src = $src = $img->getAttribute('src');

if (isset($replaces['src="'.$src.'"'])) {
continue;
}

// if starting with one slash, use local file
if (preg_match('#^/[^/]#', $normalized_src)) {
$normalized_src = $this->web_directory . parse_url($src, PHP_URL_PATH);
}

if (!isset($imgs[$normalized_src])) {
$swift_image = Swift_Image::fromPath($normalized_src);
$imgs[$normalized_src] = $message->embed($swift_image);
}

$replaces['src=\''.$src.'\''] = 'src="'.$imgs[$normalized_src].'"';
$replaces['src="' .$src.'"' ] = 'src="'.$imgs[$normalized_src].'"';
}

if (count($replaces)) {
$html = str_replace(array_keys($replaces), array_values($replaces), $html);
$message->setBody($html);
}
}

public function populateMessage(Swift_Message $message, $template_name, $context)
{
$data = $this->extractMessageContent($template_name, $context, array('subject', 'text' => 'body_text', 'html' => 'body_html'));

if (empty($data['subject']) || empty($data['text'])) {
throw new \InvalidArgumentException('The mail template must have (non-empty) subject ('.$data['subject'].') and body_text ('.$data['text'].') blocks');
}

$message->setSubject($data['subject']);

if (!empty($data['html'])) {
$message->setBody($data['html'], 'text/html')
->addPart($data['text'], 'text/plain');

$this->inlineImages($message);
} else {
$message->setBody($data['text']);
}

return $message;
}
}
141 changes: 141 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
# WMC SwiftMailer Twig bridge

This bundle provides an easy way to create email templates using Twig for the
SwiftMailer library.

This helper is inspired from
[FOSUB TwigSwiftMailer](https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Mailer/TwigSwiftMailer.php).

If you're using FOS User Bundle, we also provide a mailer service drop-in
replacement to support our additional features.

## Installation

### With Symfony
The best way to install this extension is through composer:

First, require the bundle:

```sh
composer require wemakecustom/swiftmailer-twig-bundle "^1.0"
```

Second, enable it:

```php
<?php
// app/AppKernel.php

public function registerBundles()
{
$bundles = array(
// ...
new WMC\SwiftmailerTwigBundle\WMCSwiftmailerTwigBundle(),
// ...
);
}
```

Third and finally, configure the web_directory parameter to use it:

```yaml
# config.yml

parameters:
web_directory: %kernel.root_dir%/../web
```
and you're done.
#### FOS User Bundle integration
```yaml
# config.yml

fos_user:
service:
mailer: wmc.swiftmailer_twig.fosub
```
### With a pure Swiftmailer/Twig
The best way to install this extension is through composer:
First, require the bundle:
```sh
composer require wemakecustom/swiftmailer-twig-bundle "^1.0"
```

Then give the naming strategy to doctrine's configuration:

```php
<?php

$swiftMailerTemplateHelper = new \WMC\SwiftmailerTwigBundle\TwigSwiftHelper($twig, $web_directory);
```

## Usage

It allows a Swift_Message to be populated with a Twig template. The template
expects three blocks (`subject`, `body_html`, `body_text`). If any local image
(i.e. whose `src` attribute starting with a single forward-slash `/`) with the
class `inline-image` is found in the `body_html` block, it will be inlined in
the email, allowing some eMail clients to render the image more easily.

This helper is available as the service `wmc.swiftmailer_twig`. To use it,
invoke the method `populateMessage` with these three parameters:

1. the `\Swift_Message`
2. template name
3. data array for the template

The helper depends on Symfony's component DomCrawler, Twig and SwiftMailer.


Example:

```php

$data = [];

// ...

$data['recipient'] = ['name' => 'Jonh Smith', 'email' => '[email protected]'];

$message = $mailer->createMessage()->setTo(['[email protected]' => 'John Smith']);
$swiftMailerTemplateHelper->populateMessage($message, 'AppBundle:Mail:my_email.mail.twig', $data);
$mailer->send($message);
```

```twig
{# my_email.mail.twig #}
{% block subject -%}
My email Subject
{%- endblock %}
{% block body_text %}
Hello {{ recipient.name }},
{# ... Awesome plain text email ... #}
Best Regards,
Keep being awesome!
{% endblock %}
{% block body_html %}
<h3>Hello <strong>{{ recipient.name }}</strong>,</h3>
<p>
{# ... Awesome HTML email ... #}
</p>
<p>
Best Regards,<br />
<em>Keep being awesome!</em>
</p>
{% endblock %}
```
Loading

0 comments on commit 48122f1

Please sign in to comment.