<?phpnamespace Plugin\NZCartButtonControl42\EventSubscriber;use Eccube\Event\TemplateEvent;use Plugin\NZCartButtonControl42\Repository\CartButtonControlRepository;use Symfony\Component\EventDispatcher\EventSubscriberInterface;class TemplateEventSubscriber implements EventSubscriberInterface{ /** * @var CartButtonControlRepository */ protected $cartButtonControlRepository; public function __construct(CartButtonControlRepository $cartButtonControlRepository) { $this->cartButtonControlRepository = $cartButtonControlRepository; } /** * @return array */ public static function getSubscribedEvents() { return [ 'Product/list.twig' => 'onProductList', 'Product/detail.twig' => 'onProductDetail', ]; } /** * 商品一覧ページでのカートボタン制御 * * @param TemplateEvent $event */ public function onProductList(TemplateEvent $event) { $parameters = $event->getParameters(); // カテゴリが設定されているか確認 if (isset($parameters['Category']) && $parameters['Category']) { $Category = $parameters['Category']; $categoryId = $Category->getId(); // この カテゴリの設定を取得 $control = $this->cartButtonControlRepository->findByCategoryId($categoryId); if ($control && $control->getHideCartButton()) { $event->setParameter('hide_cart_button', true); } } // 検索結果ページの場合、各商品のカテゴリをチェック if (isset($parameters['pagination']) && $parameters['pagination']) { $hideCartButtons = []; foreach ($parameters['pagination'] as $Product) { $shouldHide = false; foreach ($Product->getProductCategories() as $ProductCategory) { $categoryId = $ProductCategory->getCategory()->getId(); $control = $this->cartButtonControlRepository->findByCategoryId($categoryId); if ($control && $control->getHideCartButton()) { $shouldHide = true; break; } } $hideCartButtons[$Product->getId()] = $shouldHide; } $event->setParameter('hide_cart_buttons', $hideCartButtons); } } /** * 商品詳細ページでのカートボタン制御 * * @param TemplateEvent $event */ public function onProductDetail(TemplateEvent $event) { $parameters = $event->getParameters(); if (isset($parameters['Product']) && $parameters['Product']) { $Product = $parameters['Product']; $shouldHide = false; // 商品が所属するすべてのカテゴリをチェック foreach ($Product->getProductCategories() as $ProductCategory) { $categoryId = $ProductCategory->getCategory()->getId(); $control = $this->cartButtonControlRepository->findByCategoryId($categoryId); if ($control && $control->getHideCartButton()) { $shouldHide = true; break; } } if ($shouldHide) { $event->setParameter('hide_cart_button', true); } } }}