src/EventSubscriber/LoginSubscriber.php line 19

  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\Product;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Doctrine\Persistence\ManagerRegistry;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  8. use Symfony\Component\HttpFoundation\RequestStack;
  9. class LoginSubscriber implements EventSubscriberInterface {
  10.   private RequestStack $requestStack;
  11.   public function __construct(RequestStack $requestStack, private readonly ManagerRegistry $em) {
  12.     $this->requestStack $requestStack;
  13.   }
  14.   public function onLogin(InteractiveLoginEvent $event) {
  15.     $user $event->getAuthenticationToken()->getUser();
  16.     if (!$user || !method_exists($user'getBasket')) {
  17.       return;
  18.     }
  19.     // Postavi korpu iz baze u sesiju
  20.     $session $this->requestStack->getSession();
  21.     if (!$session->has('basket') && !is_null($user->getBasket()) && !empty($user->getBasket())) {
  22.       $basket $user->getBasket(); // Preuzmi trenutni basket korisnika
  23.       foreach ($basket as $key => $item) {
  24.         $product $this->em->getRepository(Product::class)->findOneBy([
  25.           'id' => $item['pid'],
  26.           'isOutOfStock' => true
  27.         ]);
  28.         if (!is_null($product)) {
  29.           unset($basket[$key]); // Ukloni proizvod iz niza
  30.         }
  31.       }
  32.       $session->set('basket'$basket);
  33.     }
  34.   }
  35.   public static function getSubscribedEvents(): array {
  36.     return [
  37.       InteractiveLoginEvent::class => 'onLogin',
  38.     ];
  39.   }
  40. }