src/EventSubscriber/GlobalVariablesSubscriber.php line 42

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Repository\CategoriProductRepository;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\RequestStack;
  6. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. use Twig\Environment;
  9. use App\Service\TaobaoService ;
  10. class GlobalVariablesSubscriber implements EventSubscriberInterface
  11. {
  12.     private Environment $twig;
  13.     private CategoriProductRepository $categoriProductRepository;
  14.     private RequestStack $requestStack;
  15.     private TaobaoService $taobaoService;
  16.     public function __construct(Environment $twigCategoriProductRepository $categoriProductRepositoryRequestStack $requestStackTaobaoService $taobaoService)
  17.     {
  18.         $this->twig $twig;
  19.         $this->categoriProductRepository $categoriProductRepository;
  20.         $this->requestStack $requestStack;
  21.         $this->taobaoService $taobaoService;
  22.     }
  23.     public function onKernelController(ControllerEvent $event)
  24.     {
  25.         // Récupérer l'objet Request à partir de RequestStack
  26.         $request $this->requestStack->getCurrentRequest();
  27.         if (!$request) {
  28.             return; // Sécurité : éviter d'accéder à une requête inexistante
  29.         }
  30.         // Récupération des catégories
  31.         $categories $this->categoriProductRepository->findAll();
  32.         // Récupération des données de la session
  33.         $session $request->getSession();
  34.         $countListPanierSession $session->get('listPanier', []);
  35.         // dd($countListPanierSession, count($countListPanierSession));
  36.         // Récupération des produits Taobao
  37.         // $taobaoProducts = $this->taobaoService->getAllProducts();
  38.         // dd($taobaoProducts);
  39.         // Ajout des variables globales à Twig
  40.         $this->twig->addGlobal('categories'$categories);
  41.         $this->twig->addGlobal('countListPanier'count($countListPanierSession));
  42.         // $this->twig->addGlobal('taobaoProducts', $taobaoProducts);
  43.         // dd($taobaoProducts);
  44.     }
  45.     public static function getSubscribedEvents(): array
  46.     {
  47.         return [
  48.             KernelEvents::CONTROLLER => 'onKernelController',
  49.         ];
  50.     }
  51. }