vendor/friendsofsymfony/user-bundle/src/EventListener/FlashListener.php line 72

Open in your IDE?
  1. <?php
  2. /*
  3. * This file is part of the FOSUserBundle package.
  4. *
  5. * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace FOS\UserBundle\EventListener;
  11. use FOS\UserBundle\FOSUserEvents;
  12. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  13. use Symfony\Component\HttpFoundation\RequestStack;
  14. use Symfony\Component\HttpFoundation\Session\Session;
  15. use Symfony\Contracts\EventDispatcher\Event;
  16. use Symfony\Contracts\Translation\TranslatorInterface;
  17. /**
  18. * @internal
  19. *
  20. * @final
  21. */
  22. class FlashListener implements EventSubscriberInterface
  23. {
  24. /**
  25. * @var string[]
  26. */
  27. private static $successMessages = [
  28. FOSUserEvents::CHANGE_PASSWORD_COMPLETED => 'change_password.flash.success',
  29. FOSUserEvents::PROFILE_EDIT_COMPLETED => 'profile.flash.updated',
  30. FOSUserEvents::REGISTRATION_COMPLETED => 'registration.flash.user_created',
  31. FOSUserEvents::RESETTING_RESET_COMPLETED => 'resetting.flash.success',
  32. ];
  33. /**
  34. * @var RequestStack
  35. */
  36. private $requestStack;
  37. /**
  38. * @var TranslatorInterface
  39. */
  40. private $translator;
  41. /**
  42. * FlashListener constructor.
  43. */
  44. public function __construct(RequestStack $requestStack, TranslatorInterface $translator)
  45. {
  46. $this->translator = $translator;
  47. $this->requestStack = $requestStack;
  48. }
  49. public static function getSubscribedEvents(): array
  50. {
  51. return [
  52. FOSUserEvents::CHANGE_PASSWORD_COMPLETED => 'addSuccessFlash',
  53. FOSUserEvents::PROFILE_EDIT_COMPLETED => 'addSuccessFlash',
  54. FOSUserEvents::REGISTRATION_COMPLETED => 'addSuccessFlash',
  55. FOSUserEvents::RESETTING_RESET_COMPLETED => 'addSuccessFlash',
  56. ];
  57. }
  58. /**
  59. * @param string $eventName
  60. *
  61. * @return void
  62. */
  63. public function addSuccessFlash(Event $event, $eventName)
  64. {
  65. if (!isset(self::$successMessages[$eventName])) {
  66. throw new \InvalidArgumentException('This event does not correspond to a known flash message');
  67. }
  68. $this->getSession()->getFlashBag()->add('success', $this->trans(self::$successMessages[$eventName]));
  69. }
  70. private function getSession(): Session
  71. {
  72. $request = $this->requestStack->getCurrentRequest();
  73. if (null === $request) {
  74. throw new \LogicException('Cannot get the session without an active request.');
  75. }
  76. return $request->getSession();
  77. }
  78. /**
  79. * @param string $message
  80. */
  81. private function trans($message): string
  82. {
  83. return $this->translator->trans($message, [], 'FOSUserBundle');
  84. }
  85. }