From 11ec6e4cdc4c2612d1560461ea58204c9fc83c60 Mon Sep 17 00:00:00 2001 From: Richard van Laak Date: Fri, 5 Jun 2015 14:07:50 +0200 Subject: [PATCH] Document security.switch_user event ... in the cookbook article about How to Impersonate a User. Added code sample about how to change the locale in case of a sticky locale: http://symfony.com/doc/current/cookbook/session/locale_sticky_session.html --- cookbook/security/impersonating_user.rst | 46 ++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/cookbook/security/impersonating_user.rst b/cookbook/security/impersonating_user.rst index f9003fd9b93..6845d16f8ee 100644 --- a/cookbook/security/impersonating_user.rst +++ b/cookbook/security/impersonating_user.rst @@ -151,3 +151,49 @@ setting: ), ), )); + +Events +------ + +The firewall dispatches the ``security.switch_user`` event right after the impersonation +completed. The ``SwitchUserEvent`` is passed to the listener, based on which you are able +to get the target user you impersonate. + +The cookbook article about +:doc:`Making the Locale "Sticky" during a User's Session ` +does not take any changing locale into account. The following code sample will show how to change the sticky locale: + +.. configuration-block:: + + .. code-block:: yaml + + # app/config/services.yml + services: + app.switch_user_listener: + class: AppBundle\EventListener\SwitchUserListener + tags: + - { name: kernel.event_listener, event: security.switch_user, method: onSwitchUser } + +.. caution:: + + The listener implementation assumes your ``User`` entity has ``getLocale()``. + +.. code-block:: php + + // src/AppBundle/EventListener/SwitchUserListener.pnp + + use Symfony\Component\Security\Http\Event\SwitchUserEvent; + + class SwitchUserListener + { + /** + * @param SwitchUserEvent $event + */ + public function onSwitchUser(SwitchUserEvent $event) + { + $event->getRequest()->getSession()->set( + '_locale', + $event->getTargetUser()->getLocale() + ); + } + }