George Irimiciuc George Irimiciuc - 4 months ago 51
PHP Question

Get curent user in kernel.request or kernel.request events in Symfony

I have a service in which I inject the TokenStorage and want to get the curent user.

* @Service("liip_theme.theme_request_listener")
* @Tag("kernel.event_listener", attributes={ "event"="kernel.request", "method"="onKernelRequest" })
class ThemeRequestListener
private $sam;

* @InjectParams({
* "sam" = @Inject("security.token_storage")
* })
public function __construct(TokenStorage $sam)

$this->sam = $sam;

* @param GetResponseEvent $event
public function onKernelRequest(GetResponseEvent $event)
$a = $this->sam->getToken()->getUser();

But I'm getting

Error: Call to a member function getUser() on null

I don't get this when I
, but when I run the website normally it crashes with this error. I've also deleted cache and restarted apache. I also am sure I am logged in. Var_dump()-ing it works and retrieves the curent user, but without dumping it, the website crashes.

Looking around I found out it could be related to listener priority, but I've added:

* @Tag("kernel.event_listener", attributes={ "event"="kernel.request", "method"="onKernelRequest","priority"=0 })

And changed 0 to -1, -255, 255, 1, and nothing happened.

Am I doing something wrong or is it JMSDIExtraBundle's fault?

I've also defined it like so:

class: Application\Liip\ThemeBundle\EventListener\ThemeRequestListener
arguments: [ @security.token_storage ]
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest, priority: 0 }

So it's not from JMSDI.

Another thing, it crashes only in the DEV environment. I get a Symfony toolbar crash with alert. In PROD it works fine. But I still want to solve it.

It can't be another bundle as I've tried with a fresh new 2.8.3 project with no vendor bundle aside the standard ones, just this listener and getting the same error.

Opened a GitHub issue here.

$token = $this->sam->getToken();
$a = $token ? $token->getUser() : null;

TokenStorage::getToken can return null.