src/Authentication/EventListener/JWTAuthenticationSuccessListener.php line 24

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace App\Authentication\EventListener;
  3. use App\Authentication\Entity\User;
  4. use App\Customer\Service\CustomerService;
  5. use App\Employee\Service\EmployeeService;
  6. use Doctrine\ORM\EntityNotFoundException;
  7. use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationSuccessEvent;
  8. use Symfony\Component\Security\Core\User\UserInterface;
  9. class JWTAuthenticationSuccessListener
  10. {
  11.     private CustomerService $customerService;
  12.     private EmployeeService $employeeService;
  13.     public function __construct(CustomerService $customerServiceEmployeeService $employeeService)
  14.     {
  15.         $this->customerService $customerService;
  16.         $this->employeeService $employeeService;
  17.     }
  18.     public function onAuthenticationSuccessResponse(AuthenticationSuccessEvent $event): void
  19.     {
  20.         $data $event->getData();
  21.         $user $event->getUser();
  22.         if (!$user instanceof UserInterface) {
  23.             return;
  24.         }
  25.         /** @var User $user */
  26.         $data['id'] = $user->getId();
  27.         $data['roles'] = $user->getRoles();
  28.         $customer null;
  29.         $employee null;
  30.         try {
  31.             $customer $this->customerService->getByUser($user);
  32.         } catch (EntityNotFoundException) {
  33.             // entirely ok
  34.         }
  35.         try {
  36.             $employee $this->employeeService->getByUser($user);
  37.         } catch (EntityNotFoundException) {
  38.             // entirely ok
  39.         }
  40.         if ($employee !== null) {
  41.             $data['employee_id'] = $employee->getId();
  42.             $data['firstName'] = $employee->getFirstName();
  43.         } elseif ($customer !== null) {
  44.             $data['customer_id'] = $customer->getId();
  45.             $data['firstName'] = $customer->getFirstName();
  46.         }
  47.         $event->setData($data);
  48.     }
  49. }