src/EventSubscriber/ContactEventSubscriber.php line 32

  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventSubscriber;
  4. use App\Entity\Contact;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeCrudActionEvent;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. class ContactEventSubscriber implements EventSubscriberInterface
  9. {
  10.     public function __construct(private EntityManagerInterface $entityManager)
  11.     {
  12.     }
  13.     public static function getSubscribedEvents(): array
  14.     {
  15.         return [
  16.             BeforeCrudActionEvent::class => ['beforeCrudActionEvent'],
  17.         ];
  18.     }
  19.     /**
  20.      * Set as "already read" the message when the user accesses the show page
  21.      * of the contact entity.
  22.      */
  23.     public function beforeCrudActionEvent(BeforeCrudActionEvent $event): void
  24.     {
  25.         $context $event->getAdminContext();
  26.         if ($context === null) {
  27.             return;
  28.         }
  29.         // Entity is null on the "new action".
  30.         $contact $context->getEntity()->getInstance();
  31.         if (!$contact instanceof Contact) {
  32.             return;
  33.         }
  34.         $contact->setAlreadyRead(true);
  35.         $this->entityManager->flush();
  36.     }
  37. }