src/Eccube/Controller/ProductController.php line 114

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. class ProductController extends AbstractController
  37. {
  38.     /**
  39.      * @var PurchaseFlow
  40.      */
  41.     protected $purchaseFlow;
  42.     /**
  43.      * @var CustomerFavoriteProductRepository
  44.      */
  45.     protected $customerFavoriteProductRepository;
  46.     /**
  47.      * @var CartService
  48.      */
  49.     protected $cartService;
  50.     /**
  51.      * @var ProductRepository
  52.      */
  53.     protected $productRepository;
  54.     /**
  55.      * @var BaseInfo
  56.      */
  57.     protected $BaseInfo;
  58.     /**
  59.      * @var AuthenticationUtils
  60.      */
  61.     protected $helper;
  62.     /**
  63.      * @var ProductListMaxRepository
  64.      */
  65.     protected $productListMaxRepository;
  66.     private $title '';
  67.     /**
  68.      * ProductController constructor.
  69.      *
  70.      * @param PurchaseFlow $cartPurchaseFlow
  71.      * @param CustomerFavoriteProductRepository $customerFavoriteProductRepository
  72.      * @param CartService $cartService
  73.      * @param ProductRepository $productRepository
  74.      * @param BaseInfoRepository $baseInfoRepository
  75.      * @param AuthenticationUtils $helper
  76.      * @param ProductListMaxRepository $productListMaxRepository
  77.      */
  78.     public function __construct(
  79.         PurchaseFlow $cartPurchaseFlow,
  80.         CustomerFavoriteProductRepository $customerFavoriteProductRepository,
  81.         CartService $cartService,
  82.         ProductRepository $productRepository,
  83.         BaseInfoRepository $baseInfoRepository,
  84.         AuthenticationUtils $helper,
  85.         ProductListMaxRepository $productListMaxRepository
  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.     }
  95.     /**
  96.      * 商品一覧画面.
  97.      *
  98.      * @Route("/products/list", name="product_list", methods={"GET"})
  99.      * @Template("Product/list.twig")
  100.      */
  101.     public function index(Request $requestPaginatorInterface $paginator)
  102.     {
  103.         // Doctrine SQLFilter
  104.         if ($this->BaseInfo->isOptionNostockHidden()) {
  105.             $this->entityManager->getFilters()->enable('option_nostock_hidden');
  106.         }
  107.         // handleRequestは空のqueryの場合は無視するため
  108.         if ($request->getMethod() === 'GET') {
  109.             $request->query->set('pageno'$request->query->get('pageno'''));
  110.         }
  111.         // searchForm
  112.         /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  113.         $builder $this->formFactory->createNamedBuilder(''SearchProductType::class);
  114.         if ($request->getMethod() === 'GET') {
  115.             $builder->setMethod('GET');
  116.         }
  117.         $event = new EventArgs(
  118.             [
  119.                 'builder' => $builder,
  120.             ],
  121.             $request
  122.         );
  123.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_INITIALIZE);
  124.         /* @var $searchForm \Symfony\Component\Form\FormInterface */
  125.         $searchForm $builder->getForm();
  126.         $searchForm->handleRequest($request);
  127.         // paginator
  128.         $searchData $searchForm->getData();
  129.         $qb $this->productRepository->getQueryBuilderBySearchData($searchData);
  130.         $event = new EventArgs(
  131.             [
  132.                 'searchData' => $searchData,
  133.                 'qb' => $qb,
  134.             ],
  135.             $request
  136.         );
  137.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_SEARCH);
  138.         $searchData $event->getArgument('searchData');
  139.         $query $qb->getQuery()
  140.             ->useResultCache(true$this->eccubeConfig['eccube_result_cache_lifetime_short']);
  141.         /** @var SlidingPagination $pagination */
  142.         $pagination $paginator->paginate(
  143.             $query,
  144.             !empty($searchData['pageno']) ? $searchData['pageno'] : 1,
  145.             !empty($searchData['disp_number']) ? $searchData['disp_number']->getId() : $this->productListMaxRepository->findOneBy([], ['sort_no' => 'ASC'])->getId()
  146.         );
  147.         $ids = [];
  148.         foreach ($pagination as $Product) {
  149.             $ids[] = $Product->getId();
  150.         }
  151.         $ProductsAndClassCategories $this->productRepository->findProductsWithSortedClassCategories($ids'p.id');
  152.         // addCart form
  153.         $forms = [];
  154.         foreach ($pagination as $Product) {
  155.             /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  156.             $builder $this->formFactory->createNamedBuilder(
  157.                 '',
  158.                 AddCartType::class,
  159.                 null,
  160.                 [
  161.                     'product' => $ProductsAndClassCategories[$Product->getId()],
  162.                     'allow_extra_fields' => true,
  163.                 ]
  164.             );
  165.             $addCartForm $builder->getForm();
  166.             $forms[$Product->getId()] = $addCartForm->createView();
  167.         }
  168.         $Category $searchForm->get('category_id')->getData();
  169.         // ページネーションで取得した商品に対してお気に入り情報を追加
  170.         $favorites = [];
  171.         if ($this->isGranted('ROLE_USER')) {
  172.             $Customer $this->getUser();
  173.             foreach ($pagination as $Product) {
  174.                 $favorites[$Product->getId()] = $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  175.             }
  176.         }
  177.         return [
  178.             'subtitle' => $this->getPageTitle($searchData),
  179.             'pagination' => $pagination,
  180.             'search_form' => $searchForm->createView(),
  181.             'forms' => $forms,
  182.             'Category' => $Category,
  183.             'favorites' => $favorites// お気に入り情報を追加
  184.         ];
  185.     }
  186.     /**
  187.      * 商品詳細画面.
  188.      *
  189.      * @Route("/products/detail/{id}", name="product_detail", methods={"GET"}, requirements={"id" = "\d+"})
  190.      * @Template("Product/detail.twig")
  191.      * @ParamConverter("Product", options={"repository_method" = "findWithSortedClassCategories"})
  192.      *
  193.      * @param Request $request
  194.      * @param Product $Product
  195.      *
  196.      * @return array
  197.      */
  198.     public function detail(Request $requestProduct $Product)
  199.     {
  200.         if (!$this->checkVisibility($Product)) {
  201.             throw new NotFoundHttpException();
  202.         }
  203.         // 定期購入商品かどうかをチェック
  204.         // foreach ($Product->getProductClasses() as $ProductClass)
  205.         // if ($ProductClass && $ProductClass->getSaleType()) {
  206.         //      // 定期商品の場合は、商品ごとに異なるカート識別子を使用
  207.         //      if ($ProductClass->getSaleType()->getId() == 10007 /* 定期商品のSaleType ID */) {
  208.         //         return $this->redirectToRoute('bib_detail', [
  209.         //             'id' => 9,
  210.         //             'id2' => 18
  211.         //         ]);
  212.         //     }
  213.         // }
  214.         // 商品IDによる分岐に変更
  215.         if (in_array($Product->getId(), [4018])) {
  216.             return $this->redirectToRoute('bib_detail', [
  217.                 'id' => 40,
  218.                 'id2' => 18
  219.             ]);
  220.         }else if(in_array($Product->getId(), [3842])){
  221.             return $this->redirectToRoute('bib_detail_200ppm', [
  222.                 'id' => 38,
  223.                 'id2' => 42
  224.             ]);
  225.         }
  226.         $builder $this->formFactory->createNamedBuilder(
  227.             '',
  228.             AddCartType::class,
  229.             null,
  230.             [
  231.                 'product' => $Product,
  232.                 'id_add_product_id' => false,
  233.             ]
  234.         );
  235.         $event = new EventArgs(
  236.             [
  237.                 'builder' => $builder,
  238.                 'Product' => $Product,
  239.             ],
  240.             $request
  241.         );
  242.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE);
  243.         $is_favorite false;
  244.         if ($this->isGranted('ROLE_USER')) {
  245.             $Customer $this->getUser();
  246.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  247.         }
  248.         return [
  249.             'title' => $this->title,
  250.             'subtitle' => $Product->getName(),
  251.             'form' => $builder->getForm()->createView(),
  252.             'Product' => $Product,
  253.             'is_favorite' => $is_favorite,
  254.         ];
  255.     }
  256.     /**
  257.      * お気に入り追加.
  258.      *
  259.      * @Route("/products/add_favorite/{id}", name="product_add_favorite", requirements={"id" = "\d+"}, methods={"GET", "POST"})
  260.      */
  261.     public function addFavorite(Request $requestProduct $Product)
  262.     {
  263.         $this->checkVisibility($Product);
  264.         $event = new EventArgs(
  265.             [
  266.                 'Product' => $Product,
  267.             ],
  268.             $request
  269.         );
  270.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_INITIALIZE);
  271.         if ($this->isGranted('ROLE_USER')) {
  272.             $Customer $this->getUser();
  273.             $this->customerFavoriteProductRepository->addFavorite($Customer$Product);
  274.             $this->session->getFlashBag()->set('product_detail.just_added_favorite'$Product->getId());
  275.             $event = new EventArgs(
  276.                 [
  277.                     'Product' => $Product,
  278.                 ],
  279.                 $request
  280.             );
  281.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  282.             return $this->redirectToRoute('product_detail', ['id' => $Product->getId()]);
  283.         } else {
  284.             // 非会員の場合、ログイン画面を表示
  285.             //  ログイン後の画面遷移先を設定
  286.             $this->setLoginTargetPath($this->generateUrl('product_add_favorite', ['id' => $Product->getId()], UrlGeneratorInterface::ABSOLUTE_URL));
  287.             $this->session->getFlashBag()->set('eccube.add.favorite'true);
  288.             $event = new EventArgs(
  289.                 [
  290.                     'Product' => $Product,
  291.                 ],
  292.                 $request
  293.             );
  294.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  295.             return $this->redirectToRoute('mypage_login');
  296.         }
  297.     }
  298.     /**
  299.      * お気に入り追加商品一覧画面
  300.      *
  301.      * @Route("/products/add_favorite_list/{id}", name="product_add_favorite_list", requirements={"id" = "\d+"}, methods={"GET", "POST"})
  302.      */
  303.     public function addFavoriteList(Request $requestProduct $Product)
  304.     {
  305.         $this->checkVisibility($Product);
  306.         $event = new EventArgs(
  307.             [
  308.                 'Product' => $Product,
  309.             ],
  310.             $request
  311.         );
  312.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_INITIALIZE);
  313.         if ($this->isGranted('ROLE_USER')) {
  314.             $Customer $this->getUser();
  315.             $this->customerFavoriteProductRepository->addFavorite($Customer$Product);
  316.             $this->session->getFlashBag()->set('product_detail.just_added_favorite'$Product->getId());
  317.             $event = new EventArgs(
  318.                 [
  319.                     'Product' => $Product,
  320.                 ],
  321.                 $request
  322.             );
  323.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  324.             return $this->redirectToRoute('product_list');
  325.         } else {
  326.             // 非会員の場合、ログイン画面を表示
  327.             //  ログイン後の画面遷移先を設定
  328.             $this->setLoginTargetPath($this->generateUrl('product_add_favorite', ['id' => $Product->getId()], UrlGeneratorInterface::ABSOLUTE_URL));
  329.             $this->session->getFlashBag()->set('eccube.add.favorite'true);
  330.             $event = new EventArgs(
  331.                 [
  332.                     'Product' => $Product,
  333.                 ],
  334.                 $request
  335.             );
  336.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  337.             return $this->redirectToRoute('mypage_login');
  338.         }
  339.     }
  340.     /**
  341.      * カートに追加.
  342.      *
  343.      * @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
  344.      */
  345.     public function addCart(Request $requestProduct $Product)
  346.     {
  347.         // エラーメッセージの配列
  348.         $errorMessages = [];
  349.         if (!$this->checkVisibility($Product)) {
  350.             throw new NotFoundHttpException();
  351.         }
  352.         $builder $this->formFactory->createNamedBuilder(
  353.             '',
  354.             AddCartType::class,
  355.             null,
  356.             [
  357.                 'product' => $Product,
  358.                 'id_add_product_id' => false,
  359.             ]
  360.         );
  361.         $event = new EventArgs(
  362.             [
  363.                 'builder' => $builder,
  364.                 'Product' => $Product,
  365.             ],
  366.             $request
  367.         );
  368.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE);
  369.         /* @var $form \Symfony\Component\Form\FormInterface */
  370.         $form $builder->getForm();
  371.         $form->handleRequest($request);
  372.         if (!$form->isValid()) {
  373.             throw new NotFoundHttpException();
  374.         }
  375.         $addCartData $form->getData();
  376.         log_info(
  377.             'カート追加処理開始',
  378.             [
  379.                 'product_id' => $Product->getId(),
  380.                 'product_class_id' => $addCartData['product_class_id'],
  381.                 'quantity' => $addCartData['quantity'],
  382.             ]
  383.         );
  384.         // カートへ追加
  385.         $this->cartService->addProduct($addCartData['product_class_id'], $addCartData['quantity']);
  386.         // 明細の正規化
  387.         $Carts $this->cartService->getCarts();
  388.         foreach ($Carts as $Cart) {
  389.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  390.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  391.             if ($result->hasError()) {
  392.                 $this->cartService->removeProduct($addCartData['product_class_id']);
  393.                 foreach ($result->getErrors() as $error) {
  394.                     $errorMessages[] = $error->getMessage();
  395.                 }
  396.             }
  397.             foreach ($result->getWarning() as $warning) {
  398.                 $errorMessages[] = $warning->getMessage();
  399.             }
  400.         }
  401.         $this->cartService->save();
  402.         log_info(
  403.             'カート追加処理完了',
  404.             [
  405.                 'product_id' => $Product->getId(),
  406.                 'product_class_id' => $addCartData['product_class_id'],
  407.                 'quantity' => $addCartData['quantity'],
  408.             ]
  409.         );
  410.         $event = new EventArgs(
  411.             [
  412.                 'form' => $form,
  413.                 'Product' => $Product,
  414.             ],
  415.             $request
  416.         );
  417.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE);
  418.         if ($event->getResponse() !== null) {
  419.             return $event->getResponse();
  420.         }
  421.         if ($request->isXmlHttpRequest()) {
  422.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  423.             // 初期化
  424.             $messages = [];
  425.             if (empty($errorMessages)) {
  426.                 // エラーが発生していない場合
  427.                 $done true;
  428.                 array_push($messagestrans('front.product.add_cart_complete'));
  429.             } else {
  430.                 // エラーが発生している場合
  431.                 $done false;
  432.                 $messages $errorMessages;
  433.             }
  434.             return $this->json(['done' => $done'messages' => $messages]);
  435.         } else {
  436.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  437.             foreach ($errorMessages as $errorMessage) {
  438.                 $this->addRequestError($errorMessage);
  439.             }
  440.             return $this->redirectToRoute('cart');
  441.         }
  442.     }
  443.     /**
  444.      * ページタイトルの設定
  445.      *
  446.      * @param  array|null $searchData
  447.      *
  448.      * @return str
  449.      */
  450.     protected function getPageTitle($searchData)
  451.     {
  452.         if (isset($searchData['name']) && !empty($searchData['name'])) {
  453.             return trans('front.product.search_result');
  454.         } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
  455.             return $searchData['category_id']->getName();
  456.         } else {
  457.             return trans('front.product.all_products');
  458.         }
  459.     }
  460.     /**
  461.      * 閲覧可能な商品かどうかを判定
  462.      *
  463.      * @param Product $Product
  464.      *
  465.      * @return boolean 閲覧可能な場合はtrue
  466.      */
  467.     protected function checkVisibility(Product $Product)
  468.     {
  469.         $is_admin $this->session->has('_security_admin');
  470.         // 管理ユーザの場合はステータスやオプションにかかわらず閲覧可能.
  471.         if (!$is_admin) {
  472.             // 在庫なし商品の非表示オプションが有効な場合.
  473.             // if ($this->BaseInfo->isOptionNostockHidden()) {
  474.             //     if (!$Product->getStockFind()) {
  475.             //         return false;
  476.             //     }
  477.             // }
  478.             // 公開ステータスでない商品は表示しない.
  479.             if ($Product->getStatus()->getId() !== ProductStatus::DISPLAY_SHOW) {
  480.                 return false;
  481.             }
  482.         }
  483.         return true;
  484.     }
  485. }