Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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 var_dump($a), 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:

liip_theme.theme_request_listener:
    class: Application\Liip\ThemeBundle\EventListener\ThemeRequestListener
    arguments: [ @security.token_storage ]
    tags:
        - { 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.

like image 422
George Irimiciuc Avatar asked Apr 12 '26 23:04

George Irimiciuc


1 Answers

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

TokenStorage::getToken can return null.

like image 161
Arthur Avatar answered Apr 14 '26 13:04

Arthur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!