Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 : Why getToken return null when injecting SecurityContext in a TwigExtension?

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();
    }
like image 441
Frank6 Avatar asked Feb 16 '23 07:02

Frank6


1 Answers

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();
    }
like image 195
Frank6 Avatar answered Apr 26 '23 10:04

Frank6