When I add UserInterface to my event listener, then I have following error:
Cannot autowire service "App\EventListener\ControllerListener": argument "$user" of method "__construct()" references interface "Symfony\Component\Security\Core\User\UserInterface" but no such service exists. It cannot be auto-registered because it is from a different root namespace.
I don't know what is going on, other services working fine.
Can you look for code and tell me what am I doing wrong?
~src/EventListener/ControllerListener.php
<?php
namespace App\EventListener;
use App\Entity\User;
use App\Entity\DailyWin;
use App\Controller\DailyWinController;
use Psr\Log\LoggerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
class ControllerListener extends Controller implements DailyWinController
{
private $authChecker, $user, $logger;
public function __construct(UserInterface $user, AuthorizationCheckerInterface $authChecker, LoggerInterface $logger) {
$this->user = $user;
$this->authChecker = $authChecker;
$this->logger = $logger;
}
public function onKernelController(FilterControllerEvent $event) {
if ($this->authChecker->isGranted('IS_AUTHENTICATED_FULLY') === false) return;
$this->logger->warning('Inicjowanie...');
$em = $this->getDoctrine()->getManager();
$DWrep = $em->getRepository(DailyWin::class);
$userId = $this->user->getId();
$userDailyWin = $DWrep->findOneBy(['userId' => $userId]);
$this->logger->warning(print_r($userDailyWin));
if (empty($userDailyWin)) {
$currentDate = new \DateTime(date('Y-m-d', time()));
$userDailyWin = new DailyWin();
$userDailyWin->setUserId($userId);
$userDailyWin->setMultiplier(0);
$userDailyWin->setClaimed(0);
$userDailyWin->setStreak(0);
$userDailyWin->setLastLogin($currentDate);
$em->persist($userDailyWin);
$em->flush();
}
}
}
Thanks.
The user is not a symfony service and it will not get autowired.
Try with this interface:
Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface
Then you do:
$user=$tokenStorage->getToken()->getUser();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With