app/Customize/EventListener/TwigInitializeListener.php line 51

Open in your IDE?
  1. <?php
  2. namespace Customize\EventListener;
  3. use Eccube\Repository\CategoryRepository;
  4. use Eccube\Repository\ProductCategoryRepository;
  5. use Eccube\Request\Context;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. use Twig\Environment;
  9. class TwigInitializeListener implements EventSubscriberInterface
  10. {
  11.     /**
  12.      * @var bool 初期化済かどうか.
  13.      */
  14.     protected $initialized false;
  15.     /**
  16.      * @var Environment
  17.      */
  18.     protected $twig;
  19.     /**
  20.      * @var Context
  21.      */
  22.     protected $requestContext;
  23.     protected $categoryRepository;
  24.     protected $productCategoryRepo;
  25.     /**
  26.      * TwigInitializeListener constructor.
  27.      *
  28.      * @param Environment $twig
  29.      * @param Context $context
  30.      */
  31.     public function __construct(
  32.         Environment $twig,
  33.         Context $context,
  34.         CategoryRepository $categoryRepository,
  35.         ProductCategoryRepository $productCategoryRepo
  36.     ) {
  37.         $this->twig $twig;
  38.         $this->requestContext $context;
  39.         $this->categoryRepository $categoryRepository;
  40.         $this->productCategoryRepo $productCategoryRepo;
  41.     }
  42.     public function onKernelRequest($event)
  43.     {
  44.         if ($this->initialized) {
  45.             return;
  46.         }
  47.         if ($this->requestContext->isFront()) {
  48.             $categories $this->categoryRepository->findBy([], ['sort_no' => 'DESC']);
  49.             $productCates = [];
  50.             foreach ($categories as $cate) {
  51.                 $productCates[] = [
  52.                     'category' => $cate,
  53.                     'product_cates' => $this->productCategoryRepo->findBy(
  54.                         ['category_id' => $cate['id']],
  55.                         ['sort_no' => 'DESC']
  56.                     )
  57.                 ];
  58.             }
  59.             $this->twig->addGlobal('productCates'$productCates);
  60.         }
  61.         $this->initialized true;
  62.     }
  63.     /**
  64.      * {@inheritdoc}
  65.      */
  66.     public static function getSubscribedEvents()
  67.     {
  68.         return [
  69.             KernelEvents::REQUEST => [
  70.                 ['onKernelRequest'20],
  71.             ],
  72.         ];
  73.     }
  74. }