-
-
Save vvasiloi/40ed49e336fd4be22544e3e9e1c81e9a to your computer and use it in GitHub Desktop.
Locale aware emails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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