<?php
namespace App\EventSubscriber;
use App\Entity\PhoneNumberUnsubscribes;
use App\Entity\Unsubscribes;
use App\Service\GmailAddressService;
use DateTime;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class UnsubscribesSubscriber implements EventSubscriberInterface
{
/**
* @var GmailAddressService
*/
private $gmailAddressService;
public function __construct(GmailAddressService $gmailAddressService)
{
$this->gmailAddressService = $gmailAddressService;
}
public static function getSubscribedEvents()
{
return [
BeforeEntityPersistedEvent::class => 'beforeEntityPersisted',
BeforeEntityUpdatedEvent::class => 'beforeEntityUpdated'
];
}
public function beforeEntityPersisted(BeforeEntityPersistedEvent $event)
{
$entity = $event->getEntityInstance();
if ($entity instanceof Unsubscribes) {
$sanitized = $this->gmailAddressService->sanitize(array($entity->getRecipientemail()));
$entity->setRecipientemail($sanitized[0]);
if (!$entity->getTimestamp()) {
$entity->setTimestamp(new DateTime());
}
}
if ($entity instanceof PhoneNumberUnsubscribes) {
if (!$entity->getTimestamp()) {
$entity->setTimestamp(new DateTime());
}
}
}
public function beforeEntityUpdated(BeforeEntityUpdatedEvent $event)
{
$entity = $event->getEntityInstance();
if (!$entity instanceof Unsubscribes) {
return;
}
$sanitized = $this->gmailAddressService->sanitize(array($entity->getRecipientemail()));
$entity->setRecipientemail($sanitized[0]);
}
}