4

I did exactly the answer from this post but the token property is null and the user is correctly logged in and the route is behind a firewall. Also, I am injecting the SecurityContext in other services and it works fine.

services.xml :

<service id="tc.extensions.relation_helper"
 class="TC\CoreBundle\Extensions\RelationHelperExtension">
    <argument type="service" id="security.context" />
    <tag name="twig.extension" />
</service>

My extension:

class RelationHelperExtension extends Twig_Extension
{
    /**
     * @var User 
     */
    private $user;

    public function __construct(SecurityContext $securityContext){
        $this->user = $securityContext->getToken()->getUser();
    }
Community
  • 1
  • 1
Frank6
  • 1,193
  • 1
  • 11
  • 23
  • 3
    Have you tried setting the security context to a field and using it in the `getUser()` method to get the current user instead of doing that right in the constructor? – Elnur Abdurrakhimov Sep 12 '13 at 17:47
  • Thanks @ElnurAbdurrakhimov it helps! I guess, when the security context is passed, the user is not instantiated yet – Anh Nguyen Nov 04 '14 at 07:44

2 Answers2

5

As @Elnur_Abdurrakhimov said we must cache the securityContext first and the call the getToken()->getUser() when needed.

class RelationHelperExtension extends Twig_Extension
{
    private $context;

    public function __construct(SecurityContext $securityContext){
        $this->context= $securityContext;
    }

    private function getUser(){
            return $this->context->getToken()->getUser();
    }
Frank6
  • 1,193
  • 1
  • 11
  • 23
3

To understand this behavior :

Twig_Extension are instancied BEFORE SecurityContext init sequence => at this moment SecurityContext is empty

But if you store it in a attribute, when you USE your own twig extension serviceyou are (in most of case) in a Request scope & SecurityContext is initalized with good values :)

Fabien MEYNARD
  • 597
  • 4
  • 12