<?php
namespace Customize\EventListener;
use Eccube\Repository\CategoryRepository;
use Eccube\Repository\ProductCategoryRepository;
use Eccube\Request\Context;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Twig\Environment;
class TwigInitializeListener implements EventSubscriberInterface
{
/**
* @var bool 初期化済かどうか.
*/
protected $initialized = false;
/**
* @var Environment
*/
protected $twig;
/**
* @var Context
*/
protected $requestContext;
protected $categoryRepository;
protected $productCategoryRepo;
/**
* TwigInitializeListener constructor.
*
* @param Environment $twig
* @param Context $context
*/
public function __construct(
Environment $twig,
Context $context,
CategoryRepository $categoryRepository,
ProductCategoryRepository $productCategoryRepo
) {
$this->twig = $twig;
$this->requestContext = $context;
$this->categoryRepository = $categoryRepository;
$this->productCategoryRepo = $productCategoryRepo;
}
public function onKernelRequest($event)
{
if ($this->initialized) {
return;
}
if ($this->requestContext->isFront()) {
$categories = $this->categoryRepository->findBy([], ['sort_no' => 'DESC']);
$productCates = [];
foreach ($categories as $cate) {
$productCates[] = [
'category' => $cate,
'product_cates' => $this->productCategoryRepo->findBy(
['category_id' => $cate['id']],
['sort_no' => 'DESC']
)
];
}
$this->twig->addGlobal('productCates', $productCates);
}
$this->initialized = true;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => [
['onKernelRequest', 20],
],
];
}
}