<?php
namespace App\EventListener;
use FOS\UserBundle\FOSUserEvents;
use JMS\TranslationBundle\Annotation\Ignore;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
class FlashListener implements EventSubscriberInterface
{
private static $successMessages = [
FOSUserEvents::CHANGE_PASSWORD_COMPLETED => 'change_password.flash.success',
FOSUserEvents::PROFILE_EDIT_COMPLETED => 'profile.flash.updated',
FOSUserEvents::RESETTING_RESET_COMPLETED => 'resetting.flash.success',
];
public function __construct(private readonly SessionInterface $session, private readonly TranslatorInterface $translator)
{
}
public static function getSubscribedEvents()
{
return [
FOSUserEvents::CHANGE_PASSWORD_COMPLETED => 'addSuccessFlash',
FOSUserEvents::PROFILE_EDIT_COMPLETED => 'addSuccessFlash',
FOSUserEvents::RESETTING_RESET_COMPLETED => 'addSuccessFlash',
];
}
public function addSuccessFlash($event, $eventName = null): void
{
if (!isset(self::$successMessages[$eventName])) {
throw new \InvalidArgumentException('This event does not correspond to a known flash message');
}
/**
* @Ignore
* For translation:extract
*/
$message = $this->trans(self::$successMessages[$eventName]);
$this->session->getFlashBag()->add('success', $message);
}
private function trans($message, array $params = [])
{
/**
* @Ignore
* For translation:extract
*/
$translation = $this->translator->trans($message, $params, 'FOSUserBundle');
return $translation;
}
}