<?php
/**
* Class FlashListener
* @package MWS\UserBundle\EventListener
* @author Martin Walther <martin@myweb.solutions>
*
* (c) MyWebSolutions
*/
namespace MWS\UserBundle\EventListener;
use MWS\UserBundle\MWSUserEvents;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Contracts\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Contracts\Translation\TranslatorInterface;
class FlashListener implements EventSubscriberInterface
{
/**
* @var string[]
*/
private static $successMessages = array(
MWSUserEvents::CHANGE_PASSWORD_COMPLETED => 'change_password.flash.success',
MWSUserEvents::GROUP_CREATE_COMPLETED => 'group.flash.created',
MWSUserEvents::GROUP_DELETE_COMPLETED => 'group.flash.deleted',
MWSUserEvents::GROUP_EDIT_COMPLETED => 'group.flash.updated',
MWSUserEvents::PROFILE_EDIT_COMPLETED => 'profile.flash.updated',
MWSUserEvents::REGISTRATION_COMPLETED => 'registration.flash.user_created',
MWSUserEvents::RESETTING_RESET_COMPLETED => 'resetting.flash.success',
);
/**
* @var Session
*/
private $session;
/**
* @var TranslatorInterface
*/
private $translator;
/**
* FlashListener constructor.
*
* @param RequestStack $requestStack
* @param TranslatorInterface $translator
*/
public function __construct(RequestStack $requestStack, TranslatorInterface $translator)
{
$this->session = $requestStack->getSession();
$this->translator = $translator;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return array(
MWSUserEvents::CHANGE_PASSWORD_COMPLETED => 'addSuccessFlash',
MWSUserEvents::GROUP_CREATE_COMPLETED => 'addSuccessFlash',
MWSUserEvents::GROUP_DELETE_COMPLETED => 'addSuccessFlash',
MWSUserEvents::GROUP_EDIT_COMPLETED => 'addSuccessFlash',
MWSUserEvents::PROFILE_EDIT_COMPLETED => 'addSuccessFlash',
MWSUserEvents::REGISTRATION_COMPLETED => 'addSuccessFlash',
MWSUserEvents::RESETTING_RESET_COMPLETED => 'addSuccessFlash',
);
}
/**
* @param Event $event
* @param string $eventName
*/
public function addSuccessFlash(Event $event, $eventName)
{
if (!isset(self::$successMessages[$eventName])) {
throw new \InvalidArgumentException('This event does not correspond to a known flash message');
}
$this->session->getFlashBag()->add('success', $this->trans(self::$successMessages[$eventName]));
}
/**
* @param string$message
* @param array $params
*
* @return string
*/
private function trans($message, array $params = array())
{
return $this->translator->trans($message, $params, 'MWSUserBundle');
}
}