ntyss
ntyss

Reputation: 91

EventSubscriber doesn't get triggered on event

I'm using symfony 3.2.7, and wanting to store the information of every single email sent through the app (using Swift Mailer) in my database. I'm trying to use an EventSubscriber to do that, since Swift Mailer dispatches a RESULT_SUCCESS constant from the Swift_Events_SendEvent class when an email is successfully sent. But it just doesn't work.

The file containing the EventSubscriber is definitely processed when a mail is sent (to test that, I purposedly added wrong syntax in the file and I get a syntax error when a mail is sent), but the onMailSent function apparently isn't called, since the email information isn't stored in my database. And that same function works in another context, so the problem doesn't come from the function itself.

What am I doing wrong? Here's my code:

SentMailsListener.php:

<?php

namespace Fidelise\SignUpBundle\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Fidelise\SignUpBundle\Entity\EmailsHistory;
use Swift_Events_SendEvent;

class SentMailsListener implements EventSubscriberInterface
{

    public static function getSubscribedEvents()
    {
        return [Swift_Events_SendEvent::RESULT_SUCCESS => 'onMailSent'];
    }

    public function onMailSent(Swift_Events_SendEvent $event)
    {
        $em = $this->getDoctrine()->getManager();
        $message = $event->getMessage();
        $email = new EmailsHistory();
        $email->setRecipient(key($message->getTo()));
        $email->setSubject($message->getSubject());
        $email->setBody($message->getBody());
        $email->setSender(key($message->getFrom()));
        $em->persist($email);
        $em->flush();
    }
}

services.yml:

services:
    mail_sent_subscriber:
        class: Fidelise\SignUpBundle\EventListener\SentMailsListener
        tags:
            - { name: kernel.event_subscriber }

Upvotes: 0

Views: 1011

Answers (1)

VladRia
VladRia

Reputation: 1587

What should do is to register swiftmailer plugin. It is not an event listener of event dispatcher:

<?php

namespace Fidelise\SignUpBundle\EventListener;

use Swift_Events_SendEvent;
use Swift_Events_SendListener;

class SentMailsListener implements Swift_Events_SendListener
{
    public function sendPerformed(Swift_Events_SendEvent $event): void
    {
        // ...
    }
}
services:
    mail_sent_subscriber:
        class: Fidelise\SignUpBundle\EventListener\SentMailsListener
        tags:
            - { name: swiftmailer.default.plugin }

Upvotes: 2

Related Questions