src/EventListener/FlashListener.php line 32

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use FOS\UserBundle\FOSUserEvents;
  4. use JMS\TranslationBundle\Annotation\Ignore;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  7. use Symfony\Contracts\Translation\TranslatorInterface;
  8. class FlashListener implements EventSubscriberInterface
  9. {
  10.     private static $successMessages = [
  11.         FOSUserEvents::CHANGE_PASSWORD_COMPLETED => 'change_password.flash.success',
  12.         FOSUserEvents::PROFILE_EDIT_COMPLETED => 'profile.flash.updated',
  13.         FOSUserEvents::RESETTING_RESET_COMPLETED => 'resetting.flash.success',
  14.     ];
  15.     public function __construct(private readonly SessionInterface $session, private readonly TranslatorInterface $translator)
  16.     {
  17.     }
  18.     public static function getSubscribedEvents()
  19.     {
  20.         return [
  21.             FOSUserEvents::CHANGE_PASSWORD_COMPLETED => 'addSuccessFlash',
  22.             FOSUserEvents::PROFILE_EDIT_COMPLETED => 'addSuccessFlash',
  23.             FOSUserEvents::RESETTING_RESET_COMPLETED => 'addSuccessFlash',
  24.         ];
  25.     }
  26.     public function addSuccessFlash($event$eventName null): void
  27.     {
  28.         if (!isset(self::$successMessages[$eventName])) {
  29.             throw new \InvalidArgumentException('This event does not correspond to a known flash message');
  30.         }
  31.         /**
  32.          * @Ignore
  33.          * For translation:extract
  34.          */
  35.         $message $this->trans(self::$successMessages[$eventName]);
  36.         $this->session->getFlashBag()->add('success'$message);
  37.     }
  38.     private function trans($message, array $params = [])
  39.     {
  40.         /**
  41.          * @Ignore
  42.          * For translation:extract
  43.          */
  44.         $translation $this->translator->trans($message$params'FOSUserBundle');
  45.         return $translation;
  46.     }
  47. }