Symfony2: how to display admin account name when impersonating a user account?

I want to show something like this:

Case 1: "registered as a user"

@UserName [logout]

There are no problems here, I just do:

@ {{app.user.username}} [<a href = "{{path (" logout ")}}"> logout </a>]

Case 2: "registered as ADMIN"

@AdminName [logout]

The same thing works here:

@ {{app.user.username}} [<a href = "{{path (" logout ")}}"> logout </a>]

Case 3: "registered as an ADMIN impersonating a USER"

AdminName @UserName [return]

Now the problem is:

{{ ?? .. what's here .. ?? }} @ {{app.user.username}} [<a href = "{{(app.request.getRequestUri ~ '? _switch_user = _exit')}}"> return </a>]

, ... , sipmle, :/

{# iterating through user roles to find ROLE_PREVIOUS_ADMIN #}
{% for role in app.security.token.roles %}
  {% if role.source is defined %}
    {{ role.source.user.username }}
 {% endif %}
{% endfor %}
@ {{ app.user.username }} [ <a href="{{ (app.request.getRequestUri ~ '?_switch_user=_exit') }}">return</a> ]

? TWIG → ( ) → , .

+5
1

, , , , myCustomTwigFunction ?

. http://symfony.com/doc/current/cookbook/templating/twig_extension.html twig

, Twig, ...

$roles = $this->container->get('security.context')->getToken()->getRoles();
foreach ($roles as $role) {
    if (method_exists($role, 'getSource')) {
        return ($role->getSource()->getUser()->getUsername());
    }
}

$container - DI

+4

All Articles