<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use App\Entity\Contact;
use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeCrudActionEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ContactEventSubscriber implements EventSubscriberInterface
{
private EntityManagerInterface $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
public static function getSubscribedEvents(): array
{
return [
BeforeCrudActionEvent::class => ['beforeCrudActionEvent'],
];
}
/**
* Set as "already read" the message when the user accesses the show page
* of the contact entity.
*/
public function beforeCrudActionEvent(BeforeCrudActionEvent $event): void
{
$context = $event->getAdminContext();
if ($context === null) {
return;
}
// Entity is null on the "new action".
$contact = $context->getEntity()->getInstance();
if (!$contact instanceof Contact) {
return;
}
$contact->setAlreadyRead(true);
$this->entityManager->flush();
}
}