src/Eccube/Controller/ProductController.php line 277

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