Skip to content

Instantly share code, notes, and snippets.

@vvasiloi
Created December 10, 2019 10:28
Show Gist options
  • Save vvasiloi/40ed49e336fd4be22544e3e9e1c81e9a to your computer and use it in GitHub Desktop.
Save vvasiloi/40ed49e336fd4be22544e3e9e1c81e9a to your computer and use it in GitHub Desktop.
Locale aware emails
<?php
namespace App\Email;
use Sylius\Component\Mailer\Model\EmailInterface;
use Sylius\Component\Mailer\Renderer\Adapter\AdapterInterface;
use Sylius\Component\Mailer\Renderer\RenderedEmail;
use Symfony\Contracts\Translation\LocaleAwareInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use function get_class;
use function sprintf;
final class LocaleAwareEmailRenderer implements AdapterInterface
{
/**
* @var AdapterInterface
*/
private $adapter;
/**
* @var TranslatorInterface&LocaleAwareInterface
*/
private $translator;
/**
* @param AdapterInterface $adapter
* @param TranslatorInterface $translator
*/
public function __construct(AdapterInterface $adapter, TranslatorInterface $translator)
{
if ($this->translator instanceof LocaleAwareInterface) {
throw new \InvalidArgumentException(sprintf(
'The Translator "%s" must implement %s.',
get_class($translator),
LocaleAwareInterface::class
));
}
$this->adapter = $adapter;
$this->translator = $translator;
}
public function render(EmailInterface $email, array $data = []): RenderedEmail
{
if (isset($data['_locale'])) {
$locale = $this->translator->getLocale();
$this->translator->setLocale($data['_locale']);
}
$renderedEmail = $this->adapter->render($email, $data);
if (isset($locale)) {
$this->translator->setLocale($locale);
}
return $renderedEmail;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment