Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony3 Service and Token Storage

I try to Setup a Service to retrieve a Entity from my Database. My services.yml looks like this:

app.twig_global_extension:
    class: AppBundle\Twig\GlobalExtension
    arguments: [ "@doctrine.orm.entity_manager", "@security.token_storage" ]
    tags:
        - { name: twig.extension }

And my GlobalExtension like this:

<?php
namespace AppBundle\Twig;

class GlobalExtension extends \Twig_Extension
{
    protected $em;
    protected $token_storage;

    public function __construct(\Doctrine\ORM\EntityManager $em, \Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage $token_storage)
    {
        $this->em = $em;
        $this->token_storage = $token_storage;
    }


    public function getGlobals()
    {
        return [
            'userdata' => $this->em->getRepository('AppBundle:userdata')->findOneBy(['internalid' => $this->token_storage->getToken()->getUser()->getId()]),
        ];
    }

    public function getName()
    {
        return 'app_global_extension';
    }
}

It retrieves the Right Entity but my Profiler throws a Error after the page finished loading:

BadMethodCallException in GlobalExtension.php line 18:
Call to a member function getUser() on a non-object (null)

First of all what is the Problem in this case?

$this->token_storage->getToken()->getUser()->getId()

It retrieves the Right ID but throws a Error inside the Profiler?

\Doctrine\ORM\EntityManager since this gets marked as Deprecated?

like image 867
David Avatar asked Sep 26 '22 09:09

David


1 Answers

"Call to a member function getUser() on a non-object (null)" As your code is $this->token_storage->getToken()->getUser()->getId(), $this->token_storage->getToken() has to be null in order for this error to be true. Looking at the PHPdoc for this method, you'll see:

/**
 * Returns the current security token.
 *
 * @return TokenInterface|null A TokenInterface instance or null if no authentication information is available
 */
public function getToken();

In other words, the profiler URL probably isn't behind a firewall and thus getToken() has no authentication information and is null.

In your function, make sure you take this case into account and for instance return null when then token is not available.

like image 107
Wouter J Avatar answered Dec 31 '22 21:12

Wouter J