<?php
namespace Aqarmap\Bundle\MainBundle\EventListener;
use Aqarmap\Bundle\MainBundle\Event\SNSNotificationsEvent;
use Aqarmap\Bundle\NotificationBundle\Model\SESNotificationData;
use Aqarmap\Bundle\UserBundle\Entity\User;
use Aqarmap\Bundle\UserBundle\Services\UserManager;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Bounced Email Listener
* This listener does some actions, such as, disabling user account, pause notifiers, ..etc.
*/
class BouncedEmailListener implements EventSubscriberInterface
{
private EntityManagerInterface $em;
private UserManager $userManager;
public function __construct(EntityManagerInterface $em, UserManager $userManager)
{
$this->em = $em;
$this->userManager = $userManager;
}
public function disabledAccount(SNSNotificationsEvent $event): void
{
/** @var SESNotificationData $message */
$message = $event->getMessage();
if (preg_match('/bounce/i', $message->getEventType())) {
if (preg_match('/permanent/i', $message->getBounce()->getBounceType())) {
foreach ($message->getMail()->getDestination() as $email) {
/** @var User $user */
$user = $this->em->getRepository(User::class)->findOneBy(['emailCanonical' => $email]);
if ($user) {
$user->setHasEmail(false);
$this->userManager->disable($user);
}
}
}
}
}
public function globalUnsubscribe(SNSNotificationsEvent $event): void
{
$message = $event->getMessage();
foreach ($message->getMail()->getDestination() as $email) {
/** @var User $user */
$user = $this->em->getRepository(User::class)->findOneBy(['emailCanonical' => $email]);
if ($user) {
$this->userManager->globalUnsubscribe($user);
}
}
}
public static function getSubscribedEvents(): array
{
return [
SNSNotificationsEvent::SNS_NOTIFICATION_BOUNCE => ['disabledAccount'],
SNSNotificationsEvent::SNS_NOTIFICATION_COMPLAINT => ['globalUnsubscribe'],
];
}
}