src/Eccube/Controller/ProductController.php line 118

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