src/EventSubscriber/Klaviyo/KlaviyoEmailEntered.php line 35

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber\Klaviyo;
  3. use Exception;
  4. use App\Event\EmailEntered;
  5. use App\Service\Klaviyo\KlaviyoEmail;
  6. use App\Service\Klaviyo\KlaviyoProfileService;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpKernel\Event\RequestEvent;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. use Symfony\Component\Security\Core\Security;
  11. class KlaviyoEmailEntered implements EventSubscriberInterface
  12. {
  13.     public function __construct(
  14.         private KlaviyoProfileService $klaviyoProfileService,
  15.         private KlaviyoEmail $klaviyoEmail,
  16.         private Security $security
  17.     )
  18.     {
  19.         
  20.     }
  21.     public function onEmailEntered(EmailEntered $event): void
  22.     {
  23.         try {
  24.             $this->klaviyoEmail->setEmail($event->getEmail());
  25.             $this->klaviyoProfileService->identify($event->getEmail());
  26.         } catch (Exception $e) {
  27.         }
  28.     }
  29.     public function onKernelRequest(RequestEvent $event): void
  30.     {
  31.         if (!$event->isMainRequest()) {
  32.             return;
  33.         }
  34.         try {
  35.             if (!empty($this->klaviyoEmail->getEmail())) {
  36.                 return;
  37.             }
  38.             /** @var \App\Entity\User $user */
  39.             $user $this->security->getUser();
  40.             if (!$user) {
  41.                 return;
  42.             }
  43.             $email trim(strtolower($user->getEmail()));
  44.             if (!filter_var($emailFILTER_VALIDATE_EMAIL)) {
  45.                 return;
  46.             }
  47.             $this->klaviyoEmail->setEmail($email);
  48.             $this->klaviyoProfileService->identify($email);
  49.         } catch (Exception $e) {
  50.             
  51.         }
  52.     }
  53.     public static function getSubscribedEvents(): array
  54.     {
  55.         return [
  56.             EmailEntered::NAME => 'onEmailEntered',
  57.             KernelEvents::REQUEST => 'onKernelRequest',
  58.         ];
  59.     }
  60. }