Условный сброс шаблонов электронной почты в FosUserBundle Symfony Framework

У меня есть проект в Symfony с использованием FosUserBundle и PugxMultiUserBundle, потому что мне нужно 2 пользовательских типа. Есть игроки CmsUsers и Platform.

Мне нужен способ иметь шаблоны электронной почты Fos (сброс шаблона, регистрация шаблона и т. Д.) Для каждого типа пользователя. Один шаблон сброса для CmsUser и другой шаблон для игроков. То же самое для регистрации.

Проблема возникает, потому что эти шаблоны настроены в config.yaml

fos_user:
    db_driver:       orm
    firewall_name:   api
    user_class:      PanelBundle\Entity\User
    from_email:
        address:     '%fos_from_address%'
        sender_name: '%fos_from_name%'
    service:
        mailer:      api.custom_mailer
        user_manager: pugx_user_manager
    registration:
        confirmation:
            enabled:     true
            template:    'ApiBundle:Email:confirm.email.twig'
    resetting:
        retry_ttl: 1800 # After how much seconds (30 min) user can request again pass reset
        token_ttl: 604800 # After how much seconds (1 week) user token is valid (inactive in user mailbox)
        email:
            template:    'ApiBundle:Email:resetting.email.twig'

Мне нужен способ настроить или реализовать это условно. Если пользовательский тип - CmsUser, загрузите этот шаблон, иначе загрузите другой.

<?php

namespace ApiBundle\Mailer;

use FOS\UserBundle\Mailer\TwigSwiftMailer as BaseMailer;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class CustomUserMailer extends BaseMailer
{
    public function __construct(\Swift_Mailer $mailer, UrlGeneratorInterface $router, \Twig_Environment $twig, array $parameters)
    {
        parent::__construct($mailer, $router, $twig, $parameters);
    }

    /**
     * @param string $templateName
     * @param array  $context
     * @param string $fromEmail
     * @param string $toEmail
     */
    protected function sendMessage($templateName, $context, $fromEmail, $toEmail)
    {
        // Create a new mail message.
        $message = \Swift_Message::newInstance();

        $context['images']['top']['src'] = $message->embed(\Swift_Image::fromPath(
            __DIR__.'/../../../web/assets/img/email/header.jpg'

        ));
        $context['images']['bottom']['src'] = $message->embed(\Swift_Image::fromPath(
            __DIR__.'/../../../web/assets/img/email/footer.jpg'
        ));

        $context = $this->twig->mergeGlobals($context);
        $template = $this->twig->loadTemplate($templateName);
        $subject = $template->renderBlock('subject', $context);
        $textBody = $template->renderBlock('body_text', $context);
        $htmlBody = $template->renderBlock('body_html', $context);

        $message->setSubject($subject);
        $message->setFrom($fromEmail);
        $message->setTo($toEmail);
        $message->setBody($htmlBody, 'text/html');
        $message->addPart($textBody.'text/plain');

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

1 ответ

Hy,

если вы можете деактивировать отправку электронных писем FosUserBundle и создать настраиваемого слушателя, который сделал то же самое, получите код слушателей FosUserBundle и адаптируйте его (например: добавьте if($user instanceof CmsUser) и т. д.) для отправки настраиваемых писем по типу,

Проверьте прослушиватели (EmailConfirmationListener и ResettingListener) в /vendor/friendsofsymfony/user-bundle/EventListener

Другие вопросы по тегам