src/Aqarmap/Bundle/MainBundle/EventListener/BouncedEmailListener.php line 27

  1. <?php
  2. namespace Aqarmap\Bundle\MainBundle\EventListener;
  3. use Aqarmap\Bundle\MainBundle\Event\SNSNotificationsEvent;
  4. use Aqarmap\Bundle\NotificationBundle\Model\SESNotificationData;
  5. use Aqarmap\Bundle\UserBundle\Entity\User;
  6. use Aqarmap\Bundle\UserBundle\Services\UserManager;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. /**
  10. * Bounced Email Listener
  11. * This listener does some actions, such as, disabling user account, pause notifiers, ..etc.
  12. */
  13. class BouncedEmailListener implements EventSubscriberInterface
  14. {
  15. public function __construct(private readonly EntityManagerInterface $em, private readonly UserManager $userManager)
  16. {
  17. }
  18. public function disabledAccount(SNSNotificationsEvent $event): void
  19. {
  20. /** @var SESNotificationData $message */
  21. $message = $event->getMessage();
  22. if (preg_match('/bounce/i', (string) $message->getEventType())) {
  23. if (preg_match('/permanent/i', $message->getBounce()->getBounceType())) {
  24. foreach ($message->getMail()->getDestination() as $email) {
  25. /** @var User $user */
  26. $user = $this->em->getRepository(User::class)->findOneBy(['emailCanonical' => $email]);
  27. if ($user) {
  28. $user->setHasEmail(false);
  29. $this->userManager->disable($user);
  30. }
  31. }
  32. }
  33. }
  34. }
  35. public function globalUnsubscribe(SNSNotificationsEvent $event): void
  36. {
  37. $message = $event->getMessage();
  38. foreach ($message->getMail()->getDestination() as $email) {
  39. /** @var User $user */
  40. $user = $this->em->getRepository(User::class)->findOneBy(['emailCanonical' => $email]);
  41. if ($user) {
  42. $this->userManager->globalUnsubscribe($user);
  43. }
  44. }
  45. }
  46. public static function getSubscribedEvents(): array
  47. {
  48. return [
  49. SNSNotificationsEvent::SNS_NOTIFICATION_BOUNCE => ['disabledAccount'],
  50. SNSNotificationsEvent::SNS_NOTIFICATION_COMPLAINT => ['globalUnsubscribe'],
  51. ];
  52. }
  53. }