<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\Contact;
use App\Entity\Gender;
use App\Mailer\Contact\ContactMailerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class ContactSubscriber implements EventSubscriberInterface
{
private ContactMailerInterface $mailer;
/**
* @param ContactMailerInterface $mailer
*/
public function __construct(ContactMailerInterface $mailer)
{
$this->mailer = $mailer;
}
/**
* @return array[]
*/
public static function getSubscribedEvents(): array
{
return [
KernelEvents::VIEW => [
['onPost', EventPriorities::POST_WRITE],
['prePersist', EventPriorities::PRE_WRITE]
]
];
}
/**
* @param ViewEvent $event
*
* @return void
*/
public function onPost(ViewEvent $event): void
{
$contact = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if ($contact instanceof Contact && Request::METHOD_POST === $method && $contact->getRecommender() !== null) {
$this->mailer->notifyRecommended($contact);
}
}
/**
* @param ViewEvent $event
* @return void
*/
public function prePersist(ViewEvent $event): void
{
$contact = $event->getControllerResult();
$isPutMethod = $event->getRequest()->getMethod() === Request::METHOD_PUT;
$isPostMethod = $event->getRequest()->getMethod() === Request::METHOD_POST;
if ($contact instanceof Contact && ($isPutMethod || $isPostMethod) && $contact->getIsPreoccupation()) {
if ($contact->isCompany()) {
$contact->setIsPreoccupation(false);
$contact->setProxyContact(null);
}
}
}
}