Symfony3 Maintenance and Token Storage

I am trying to configure a service to retrieve an entity from my database. My services.yml is as follows:

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

And my GlobalExtension is 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 an error after the page has finished loading:

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

First, what is the problem?

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

It retrieves the correct identifier, but throws an error inside Profiler?

\ Doctrine \ ORM \ EntityManager, so how does it get marked as deprecated?

+5
source share
1 answer

"Calling the member function getUser () in a non-object (null) . Since your code is $this->token_storage->getToken()->getUser()->getId() , $this->token_storage->getToken() must be null for this error to be true Looking at PHPdoc for this method , you will 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 is probably not behind the firewall, and therefore getToken() has no authentication information and is null.

In your function, make sure that you take this case into account and, for example, return null when the token is unavailable.

+4
source

Source: https://habr.com/ru/post/1242943/


All Articles