src/Eccube/Controller/ProductController.php line 276

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