src/Eccube/Controller/ProductController.php line 257

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of EC-CUBE
  4.  *
  5.  * Copyright(c) EC-CUBE CO.,LTD. All Rights Reserved.
  6.  *
  7.  * http.www.ec-cube.co.jp/
  8.  *
  9.  * For the full copyright and license information, please view the LICENSE
  10.  * file that was distributed with this source code.
  11.  */
  12. namespace Eccube\Controller;
  13. use Eccube\Entity\BaseInfo;
  14. use Eccube\Entity\Master\ProductStatus;
  15. use Eccube\Entity\Product;
  16. use Eccube\Event\EccubeEvents;
  17. use Eccube\Event\EventArgs;
  18. use Eccube\Form\Type\AddCartType;
  19. use Eccube\Form\Type\SearchProductType;
  20. use Eccube\Repository\BaseInfoRepository;
  21. use Eccube\Repository\CustomerFavoriteProductRepository;
  22. use Eccube\Repository\Master\ProductListMaxRepository;
  23. use Eccube\Repository\ProductRepository;
  24. use Eccube\Service\CartService;
  25. use Eccube\Service\PurchaseFlow\PurchaseContext;
  26. use Eccube\Service\PurchaseFlow\PurchaseFlow;
  27. use Knp\Bundle\PaginatorBundle\Pagination\SlidingPagination;
  28. use Knp\Component\Pager\PaginatorInterface;
  29. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  30. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  31. use Symfony\Component\HttpFoundation\Request;
  32. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  33. use Symfony\Component\Routing\Annotation\Route;
  34. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  35. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  36. // ★ 追加:レビューのRepositoryを呼び出す
  37. use Plugin\ProductReview42\Repository\ProductReviewRepository;
  38. class ProductController extends AbstractController
  39. {
  40.     /**
  41.      * @var PurchaseFlow
  42.      */
  43.     protected $purchaseFlow;
  44.     /**
  45.      * @var CustomerFavoriteProductRepository
  46.      */
  47.     protected $customerFavoriteProductRepository;
  48.     /**
  49.      * @var CartService
  50.      */
  51.     protected $cartService;
  52.     /**
  53.      * @var ProductRepository
  54.      */
  55.     protected $productRepository;
  56.     // ★ 追加:レビューのRepositoryを格納する変数
  57.     /**
  58.      * @var ProductReviewRepository
  59.      */
  60.     protected $productReviewRepository;
  61.     /**
  62.      * @var BaseInfo
  63.      */
  64.     protected $BaseInfo;
  65.     /**
  66.      * @var AuthenticationUtils
  67.      */
  68.     protected $helper;
  69.     /**
  70.      * @var ProductListMaxRepository
  71.      */
  72.     protected $productListMaxRepository;
  73.     private $title '';
  74.     /**
  75.      * ProductController constructor.
  76.      */
  77.     public function __construct(
  78.         PurchaseFlow $cartPurchaseFlow,
  79.         CustomerFavoriteProductRepository $customerFavoriteProductRepository,
  80.         CartService $cartService,
  81.         ProductRepository $productRepository,
  82.         BaseInfoRepository $baseInfoRepository,
  83.         AuthenticationUtils $helper,
  84.         ProductListMaxRepository $productListMaxRepository,
  85.         ProductReviewRepository $productReviewRepository // ★ 追加:引数にレビューのRepositoryを追加
  86.     ) {
  87.         $this->purchaseFlow $cartPurchaseFlow;
  88.         $this->customerFavoriteProductRepository $customerFavoriteProductRepository;
  89.         $this->cartService $cartService;
  90.         $this->productRepository $productRepository;
  91.         $this->BaseInfo $baseInfoRepository->get();
  92.         $this->helper $helper;
  93.         $this->productListMaxRepository $productListMaxRepository;
  94.         $this->productReviewRepository $productReviewRepository// ★ 追加:変数にセット
  95.     }
  96.     /**
  97.      * 商品一覧画面.
  98.      *
  99.      * @Route("/products/list", name="product_list", methods={"GET"})
  100.      * @Template("Product/list.twig")
  101.      */
  102.     public function index(Request $requestPaginatorInterface $paginator)
  103.     {
  104.         // ... ここから $pagination = $paginator->paginate(...) の行までは変更ありません ...
  105.         // Doctrine SQLFilter
  106.         if ($this->BaseInfo->isOptionNostockHidden()) {
  107.             $this->entityManager->getFilters()->enable('option_nostock_hidden');
  108.         }
  109.         // handleRequestは空のqueryの場合は無視するため
  110.         if ($request->getMethod() === 'GET') {
  111.             $request->query->set('pageno'$request->query->get('pageno'''));
  112.         }
  113.         // searchForm
  114.         /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  115.         $builder $this->formFactory->createNamedBuilder(''SearchProductType::class);
  116.         if ($request->getMethod() === 'GET') {
  117.             $builder->setMethod('GET');
  118.         }
  119.         $event = new EventArgs(
  120.             [
  121.                 'builder' => $builder,
  122.             ],
  123.             $request
  124.         );
  125.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_INITIALIZE);
  126.         /* @var $searchForm \Symfony\Component\Form\FormInterface */
  127.         $searchForm $builder->getForm();
  128.         $searchForm->handleRequest($request);
  129.         // paginator
  130.         $searchData $searchForm->getData();
  131.         $qb $this->productRepository->getQueryBuilderBySearchData($searchData);
  132.         // ▼▼▼ 会員限定商品を一覧から除外するコード ▼▼▼
  133.         // ログインしていない場合のみ、一覧から除外する
  134.         if (!$this->isGranted('ROLE_USER')) {
  135.         // 会員限定にしたい商品IDをここに入力します
  136.         $members_only_product_ids = [300137289290291];
  137.         // クエリに「これらの商品IDは除外する」という条件を追加
  138.         $qb->andWhere($qb->expr()->notIn('p.id'':members_only_product_ids'))
  139.         ->setParameter('members_only_product_ids'$members_only_product_ids);
  140.         }
  141.         // ▲▲▲ ここまで ▲▲▲
  142.         $event = new EventArgs(
  143.             [
  144.                 'searchData' => $searchData,
  145.                 'qb' => $qb,
  146.             ],
  147.             $request
  148.         );
  149.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_SEARCH);
  150.         $searchData $event->getArgument('searchData');
  151.         $query $qb->getQuery()
  152.             ->useResultCache(true$this->eccubeConfig['eccube_result_cache_lifetime_short']);
  153.         /** @var SlidingPagination $pagination */
  154.         $pagination $paginator->paginate(
  155.             $query,
  156.             !empty($searchData['pageno']) ? $searchData['pageno'] : 1,
  157.             !empty($searchData['disp_number']) ? $searchData['disp_number']->getId() : $this->productListMaxRepository->findOneBy([], ['sort_no' => 'ASC'])->getId()
  158.         );
  159.         // ... ここから下を修正・追加します ...
  160.         $ids = [];
  161.         foreach ($pagination as $Product) {
  162.             $ids[] = $Product->getId();
  163.         }
  164.         // ★ 追加:レビューの統計情報を取得する処理
  165.         $review_stats = [];
  166.         if (!empty($ids)) {
  167.             $qb_review $this->productReviewRepository->createQueryBuilder('pr');
  168.             $qb_review->select('IDENTITY(pr.Product) as product_id, COUNT(pr.id) as review_count, AVG(pr.recommend_level) as avg_rating')
  169.                 ->where('pr.Status = :Status')
  170.                 ->andWhere($qb_review->expr()->in('pr.Product'':product_ids'))
  171.                 ->groupBy('pr.Product')
  172.                 ->setParameter('Status'1)
  173.                 ->setParameter('product_ids'$ids);
  174.             $results $qb_review->getQuery()->getResult();
  175.             foreach ($results as $result) {
  176.                 $review_stats[$result['product_id']] = $result;
  177.             }
  178.         }
  179.         $ProductsAndClassCategories $this->productRepository->findProductsWithSortedClassCategories($ids'p.id');
  180.         // addCart form
  181.         $forms = [];
  182.         foreach ($pagination as $Product) {
  183.             /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  184.             $builder $this->formFactory->createNamedBuilder(
  185.                 '',
  186.                 AddCartType::class,
  187.                 null,
  188.                 [
  189.                     'product' => $ProductsAndClassCategories[$Product->getId()],
  190.                     'allow_extra_fields' => true,
  191.                 ]
  192.             );
  193.             $addCartForm $builder->getForm();
  194.             $forms[$Product->getId()] = $addCartForm->createView();
  195.         }
  196.         $Category $searchForm->get('category_id')->getData();
  197.         return [
  198.             'subtitle' => $this->getPageTitle($searchData),
  199.             'pagination' => $pagination,
  200.             'search_form' => $searchForm->createView(),
  201.             'forms' => $forms,
  202.             'Category' => $Category,
  203.             'review_stats' => $review_stats// ★ 追加:取得したレビュー統計情報をテンプレートに渡す
  204.         ];
  205.     }
  206.     /**
  207.      * 商品詳細画面.
  208.      *
  209.      * @Route("/products/detail/{id}", name="product_detail", methods={"GET"}, requirements={"id" = "\d+"})
  210.      * @Template("Product/detail.twig")
  211.      * @ParamConverter("Product", options={"repository_method" = "findWithSortedClassCategories"})
  212.      *
  213.      * @param Request $request
  214.      * @param Product $Product
  215.      *
  216.      * @return array
  217.      */
  218.     public function detail(Request $requestProduct $Product)
  219.     {
  220.         // ▼▼▼ このコードブロックをここに追加します ▼▼▼
  221.         $members_only_product_ids = [300137289290291];
  222.         if (in_array($Product->getId(), $members_only_product_ids) && !$this->isGranted('ROLE_USER')) {
  223.             $this->addFlash('eccube.login.target.path'$request->getRequestUri());
  224.             return $this->redirectToRoute('mypage_login');
  225.         }
  226.         // ▲▲▲ ここまで ▲▲▲
  227.       
  228.         if (!$this->checkVisibility($Product)) {
  229.             throw new NotFoundHttpException();
  230.         }
  231.         $builder $this->formFactory->createNamedBuilder(
  232.             '',
  233.             AddCartType::class,
  234.             null,
  235.             [
  236.                 'product' => $Product,
  237.                 'id_add_product_id' => false,
  238.             ]
  239.         );
  240.         $event = new EventArgs(
  241.             [
  242.                 'builder' => $builder,
  243.                 'Product' => $Product,
  244.             ],
  245.             $request
  246.         );
  247.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE);
  248.         $is_favorite false;
  249.         if ($this->isGranted('ROLE_USER')) {
  250.             $Customer $this->getUser();
  251.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  252.         }
  253.         return [
  254.             'title' => $this->title,
  255.             'subtitle' => $Product->getName(),
  256.             'form' => $builder->getForm()->createView(),
  257.             'Product' => $Product,
  258.             'is_favorite' => $is_favorite,
  259.         ];
  260.     }
  261.     /**
  262.      * お気に入り追加.
  263.      *
  264.      * @Route("/products/add_favorite/{id}", name="product_add_favorite", requirements={"id" = "\d+"}, methods={"GET", "POST"})
  265.      */
  266.     public function addFavorite(Request $requestProduct $Product)
  267.     {
  268.         $this->checkVisibility($Product);
  269.         $event = new EventArgs(
  270.             [
  271.                 'Product' => $Product,
  272.             ],
  273.             $request
  274.         );
  275.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_INITIALIZE);
  276.         if ($this->isGranted('ROLE_USER')) {
  277.             $Customer $this->getUser();
  278.             $this->customerFavoriteProductRepository->addFavorite($Customer$Product);
  279.             $this->session->getFlashBag()->set('product_detail.just_added_favorite'$Product->getId());
  280.             $event = new EventArgs(
  281.                 [
  282.                     'Product' => $Product,
  283.                 ],
  284.                 $request
  285.             );
  286.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  287.             return $this->redirectToRoute('product_detail', ['id' => $Product->getId()]);
  288.         } else {
  289.             // 非会員の場合、ログイン画面を表示
  290.             //  ログイン後の画面遷移先を設定
  291.             $this->setLoginTargetPath($this->generateUrl('product_add_favorite', ['id' => $Product->getId()], UrlGeneratorInterface::ABSOLUTE_URL));
  292.             $this->session->getFlashBag()->set('eccube.add.favorite'true);
  293.             $event = new EventArgs(
  294.                 [
  295.                     'Product' => $Product,
  296.                 ],
  297.                 $request
  298.             );
  299.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  300.             return $this->redirectToRoute('mypage_login');
  301.         }
  302.     }
  303.     /**
  304.      * カートに追加.
  305.      *
  306.      * @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
  307.      */
  308.     public function addCart(Request $requestProduct $Product)
  309.     {
  310.         // エラーメッセージの配列
  311.         $errorMessages = [];
  312.         if (!$this->checkVisibility($Product)) {
  313.             throw new NotFoundHttpException();
  314.         }
  315.         $builder $this->formFactory->createNamedBuilder(
  316.             '',
  317.             AddCartType::class,
  318.             null,
  319.             [
  320.                 'product' => $Product,
  321.                 'id_add_product_id' => false,
  322.             ]
  323.         );
  324.         $event = new EventArgs(
  325.             [
  326.                 'builder' => $builder,
  327.                 'Product' => $Product,
  328.             ],
  329.             $request
  330.         );
  331.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE);
  332.         /* @var $form \Symfony\Component\Form\FormInterface */
  333.         $form $builder->getForm();
  334.         $form->handleRequest($request);
  335.         if (!$form->isValid()) {
  336.             throw new NotFoundHttpException();
  337.         }
  338.         $addCartData $form->getData();
  339.         log_info(
  340.             'カート追加処理開始',
  341.             [
  342.                 'product_id' => $Product->getId(),
  343.                 'product_class_id' => $addCartData['product_class_id'],
  344.                 'quantity' => $addCartData['quantity'],
  345.             ]
  346.         );
  347.         // カートへ追加
  348.         $this->cartService->addProduct($addCartData['product_class_id'], $addCartData['quantity']);
  349.         // 明細の正規化
  350.         $Carts $this->cartService->getCarts();
  351.         foreach ($Carts as $Cart) {
  352.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  353.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  354.             if ($result->hasError()) {
  355.                 $this->cartService->removeProduct($addCartData['product_class_id']);
  356.                 foreach ($result->getErrors() as $error) {
  357.                     $errorMessages[] = $error->getMessage();
  358.                 }
  359.             }
  360.             foreach ($result->getWarning() as $warning) {
  361.                 $errorMessages[] = $warning->getMessage();
  362.             }
  363.         }
  364.         $this->cartService->save();
  365.         log_info(
  366.             'カート追加処理完了',
  367.             [
  368.                 'product_id' => $Product->getId(),
  369.                 'product_class_id' => $addCartData['product_class_id'],
  370.                 'quantity' => $addCartData['quantity'],
  371.             ]
  372.         );
  373.         $event = new EventArgs(
  374.             [
  375.                 'form' => $form,
  376.                 'Product' => $Product,
  377.             ],
  378.             $request
  379.         );
  380.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE);
  381.         if ($event->getResponse() !== null) {
  382.             return $event->getResponse();
  383.         }
  384.         if ($request->isXmlHttpRequest()) {
  385.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  386.             // 初期化
  387.             $messages = [];
  388.             if (empty($errorMessages)) {
  389.                 // エラーが発生していない場合
  390.                 $done true;
  391.                 array_push($messagestrans('front.product.add_cart_complete'));
  392.             } else {
  393.                 // エラーが発生している場合
  394.                 $done false;
  395.                 $messages $errorMessages;
  396.             }
  397.             return $this->json(['done' => $done'messages' => $messages]);
  398.         } else {
  399.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  400.             foreach ($errorMessages as $errorMessage) {
  401.                 $this->addRequestError($errorMessage);
  402.             }
  403.             return $this->redirectToRoute('cart');
  404.         }
  405.     }
  406.     /**
  407.      * ページタイトルの設定
  408.      *
  409.      * @param  array|null $searchData
  410.      *
  411.      * @return str
  412.      */
  413.     protected function getPageTitle($searchData)
  414.     {
  415.         if (isset($searchData['name']) && !empty($searchData['name'])) {
  416.             return trans('front.product.search_result');
  417.         } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
  418.             return $searchData['category_id']->getName();
  419.         } else {
  420.             return trans('front.product.all_products');
  421.         }
  422.     }
  423.     /**
  424.      * 閲覧可能な商品かどうかを判定
  425.      *
  426.      * @param Product $Product
  427.      *
  428.      * @return boolean 閲覧可能な場合はtrue
  429.      */
  430.     protected function checkVisibility(Product $Product)
  431.     {
  432.         $is_admin $this->session->has('_security_admin');
  433.         // 管理ユーザの場合はステータスやオプションにかかわらず閲覧可能.
  434.         if (!$is_admin) {
  435.             // 在庫なし商品の非表示オプションが有効な場合.
  436.             // if ($this->BaseInfo->isOptionNostockHidden()) {
  437.             //     if (!$Product->getStockFind()) {
  438.             //         return false;
  439.             //     }
  440.             // }
  441.             // 公開ステータスでない商品は表示しない.
  442.             if ($Product->getStatus()->getId() !== ProductStatus::DISPLAY_SHOW) {
  443.                 return false;
  444.             }
  445.         }
  446.         return true;
  447.     }
  448. }