app/Customize/EventListener/TwigAddParamsListener.php line 19

Open in your IDE?
  1. <?php
  2. // /app/Customize/EventListener/TwigAddParamsListener.php
  3. namespace Customize\EventListener;
  4. use Customize\Repository\RankingRepository;
  5. use Eccube\Event\TemplateEvent;
  6. use Eccube\Repository\ProductRepository;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. class TwigAddParamsListener implements EventSubscriberInterface
  9. {
  10.     /**
  11.      * コンストラクタ
  12.      * 
  13.      * @param RankingRepository $rankingRepository 売上ランキングのリポジトリ
  14.      * @param ProductRepository $productRepository 商品リポジトリ
  15.      */
  16.     public function __construct(
  17.         RankingRepository $rankingRepository,
  18.         ProductRepository $productRepository
  19.     ) {
  20.         $this->rankingRepository $rankingRepository;
  21.         $this->productRepository $productRepository;
  22.     }
  23.     /**
  24.      * テンプレートイベントのリスナー
  25.      * 売上ランキングをテンプレートに渡すための処理
  26.      * 
  27.      * @param TemplateEvent $event テンプレートイベント
  28.      */
  29.     public function onRanking(TemplateEvent $event)
  30.     {
  31.         // 現在のテンプレートのパラメータを取得
  32.         $parameters $event->getParameters();
  33.         // 売上ランキングのデータを取得
  34.         $ProductClasses $this->rankingRepository->getProductsRanking();
  35.         $event->setParameters($parameters);
  36.         $sums = [];
  37.         $Products = [];
  38.         if (!empty($ProductClasses)) {
  39.             foreach ($ProductClasses as $item) {
  40.                 if (!isset($sums[$item['product_id']])) {
  41.                     $sums[$item['product_id']] = 0;
  42.                 }
  43.                 $sums[$item['product_id']] += $item['total_price'];
  44.             }
  45.             // 合計をtotal_priceで並び替え
  46.             arsort($sums);
  47.             // 結果を表示(必要に応じて)
  48.             foreach ($sums as $productId => $totalPrice) {
  49.                 // 商品IDに基づいて商品情報を取得
  50.                 $Products[] = current($this->productRepository->findBy(['id' => $productId]));
  51.             }
  52.         }
  53.         // // テンプレートにランキング商品を渡す
  54.         $parameters['rankingProducts'] = $Products;
  55.         $event->setParameters($parameters);
  56.     }
  57.     /**
  58.      * イベントサブスクライバーを定義
  59.      * 
  60.      * @return array イベントとメソッドのマッピング
  61.      */
  62.     public static function getSubscribedEvents()
  63.     {
  64.         return [
  65.             // 'Block/ranking.twig'テンプレートに対するイベントリスナーを登録
  66.             'Block/ranking.twig' => 'onRanking',
  67.         ];
  68.     }
  69. }