src/Eccube/Controller/ProductController.php line 115

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\ProductListOrderBy;
  15. use Eccube\Entity\Master\ProductStatus;
  16. use Eccube\Entity\Product;
  17. use Eccube\Event\EccubeEvents;
  18. use Eccube\Event\EventArgs;
  19. use Eccube\Form\Type\AddCartType;
  20. use Eccube\Form\Type\SearchProductType;
  21. use Eccube\Repository\BaseInfoRepository;
  22. use Eccube\Repository\CustomerFavoriteProductRepository;
  23. use Eccube\Repository\Master\ProductListMaxRepository;
  24. use Eccube\Repository\ProductRepository;
  25. use Eccube\Service\CartService;
  26. use Eccube\Service\PurchaseFlow\PurchaseContext;
  27. use Eccube\Service\PurchaseFlow\PurchaseFlow;
  28. use Knp\Bundle\PaginatorBundle\Pagination\SlidingPagination;
  29. use Knp\Component\Pager\PaginatorInterface;
  30. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  31. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  32. use Symfony\Component\HttpFoundation\Request;
  33. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  34. use Symfony\Component\Routing\Annotation\Route;
  35. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  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", methods={"GET"})
  100.      * @Template("Product/list.twig")
  101.      */
  102.     public function index(Request $requestPaginatorInterface $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($eventEccubeEvents::FRONT_PRODUCT_INDEX_INITIALIZE);
  125.         /* @var $searchForm \Symfony\Component\Form\FormInterface */
  126.         $searchForm $builder->getForm();
  127.         $searchForm->handleRequest($request);
  128.         // paginator
  129.         $searchData $searchForm->getData();
  130.         $searchData['orderby'] = $request->get('orderby');
  131.         $qb $this->productRepository->getQueryBuilderByProductListSearchData($searchData);
  132.         $event = new EventArgs(
  133.             [
  134.                 'searchData' => $searchData,
  135.                 'qb' => $qb,
  136.             ],
  137.             $request
  138.         );
  139.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_SEARCH);
  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.             $this->eccubeConfig->get('eccube_default_product_list_page_count'// default page limit
  148. //            !empty($searchData['disp_number']) ? $searchData['disp_number']->getId() : $this->productListMaxRepository->findOneBy([], ['sort_no' => 'ASC'])->getId(),
  149. //            !empty($searchData['orderby']) ? $searchData['orderby'] : $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.         $Category $searchForm->get('category_id')->getData();
  173.         $OrderList $this->entityManager->getRepository(ProductListOrderBy::class)->findBy([], ['sort_no' => 'DESC']);
  174.         $user $this->getUser();
  175.         return [
  176.             'subtitle' => $this->getPageTitle($searchData),
  177.             'pagination' => $pagination,
  178.             'search_form' => $searchForm->createView(),
  179.             'forms' => $forms,
  180.             'Category' => $Category,
  181.             'OrderList' => $OrderList,
  182.             'User' => $user,
  183.         ];
  184.     }
  185.     /**
  186.      * 商品詳細画面.
  187.      *
  188.      * @Route("/products/detail/{id}", name="product_detail", methods={"GET"}, requirements={"id" = "\d+"})
  189.      * @Template("Product/detail.twig")
  190.      * @ParamConverter("Product", options={"repository_method" = "findWithSortedClassCategories"})
  191.      *
  192.      * @param Request $request
  193.      * @param Product $Product
  194.      *
  195.      * @return array
  196.      */
  197.     public function detail(Request $requestProduct $Product)
  198.     {
  199.         if (!$this->checkVisibility($Product)) {
  200.             throw new NotFoundHttpException();
  201.         }
  202.         $builder $this->formFactory->createNamedBuilder(
  203.             '',
  204.             AddCartType::class,
  205.             null,
  206.             [
  207.                 'product' => $Product,
  208.                 'id_add_product_id' => false,
  209.             ]
  210.         );
  211.         $event = new EventArgs(
  212.             [
  213.                 'builder' => $builder,
  214.                 'Product' => $Product,
  215.             ],
  216.             $request
  217.         );
  218.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE);
  219.         $is_favorite false;
  220.         if ($this->isGranted('ROLE_USER')) {
  221.             $Customer $this->getUser();
  222.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  223.         }
  224.         $user $this->getUser();
  225.         return [
  226.             'title' => $this->title,
  227.             'subtitle' => $Product->getName(),
  228.             'form' => $builder->getForm()->createView(),
  229.             'Product' => $Product,
  230.             'is_favorite' => $is_favorite,
  231.             'User' => $user,
  232.         ];
  233.     }
  234.     /**
  235.      * お気に入り追加.
  236.      *
  237.      * @Route("/products/add_favorite/{id}", name="product_add_favorite", requirements={"id" = "\d+"}, methods={"GET", "POST"})
  238.      */
  239.     public function addFavorite(Request $requestProduct $Product)
  240.     {
  241.         $this->checkVisibility($Product);
  242.         $event = new EventArgs(
  243.             [
  244.                 'Product' => $Product,
  245.             ],
  246.             $request
  247.         );
  248.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_INITIALIZE);
  249.         if ($this->isGranted('ROLE_USER')) {
  250.             $Customer $this->getUser();
  251.             $this->customerFavoriteProductRepository->addFavorite($Customer$Product);
  252.             $this->session->getFlashBag()->set('product_detail.just_added_favorite'$Product->getId());
  253.             $event = new EventArgs(
  254.                 [
  255.                     'Product' => $Product,
  256.                 ],
  257.                 $request
  258.             );
  259.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  260.             return $this->redirectToRoute('product_detail', ['id' => $Product->getId()]);
  261.         } else {
  262.             // 非会員の場合、ログイン画面を表示
  263.             //  ログイン後の画面遷移先を設定
  264.             $this->setLoginTargetPath($this->generateUrl('product_add_favorite', ['id' => $Product->getId()], UrlGeneratorInterface::ABSOLUTE_URL));
  265.             $this->session->getFlashBag()->set('eccube.add.favorite'true);
  266.             $event = new EventArgs(
  267.                 [
  268.                     'Product' => $Product,
  269.                 ],
  270.                 $request
  271.             );
  272.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  273.             return $this->redirectToRoute('mypage_login');
  274.         }
  275.     }
  276.     /**
  277.      * カートに追加.
  278.      *
  279.      * @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
  280.      */
  281.     public function addCart(Request $requestProduct $Product)
  282.     {
  283.         // from cart to login
  284. //        if (!$this->isGranted('ROLE_USER')) {
  285. //            return $this->redirectToRoute('mypage_login');
  286. //        }
  287.         // エラーメッセージの配列
  288.         $errorMessages = [];
  289.         if (!$this->checkVisibility($Product)) {
  290.             throw new NotFoundHttpException();
  291.         }
  292.         $builder $this->formFactory->createNamedBuilder(
  293.             '',
  294.             AddCartType::class,
  295.             null,
  296.             [
  297.                 'product' => $Product,
  298.                 'id_add_product_id' => false,
  299.             ]
  300.         );
  301.         $event = new EventArgs(
  302.             [
  303.                 'builder' => $builder,
  304.                 'Product' => $Product,
  305.             ],
  306.             $request
  307.         );
  308.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE);
  309.         /* @var $form \Symfony\Component\Form\FormInterface */
  310.         $form $builder->getForm();
  311.         $form->handleRequest($request);
  312.         if (!$form->isValid()) {
  313.             throw new NotFoundHttpException();
  314.         }
  315.         $addCartData $form->getData();
  316.         log_info(
  317.             'カート追加処理開始',
  318.             [
  319.                 'product_id' => $Product->getId(),
  320.                 'product_class_id' => $addCartData['product_class_id'],
  321.                 'quantity' => $addCartData['quantity'],
  322.             ]
  323.         );
  324.         // カートへ追加
  325.         $this->cartService->addProduct($addCartData['product_class_id'], $addCartData['quantity']);
  326.         // 明細の正規化
  327.         $Carts $this->cartService->getCarts();
  328.         foreach ($Carts as $Cart) {
  329.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  330.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  331.             if ($result->hasError()) {
  332.                 $this->cartService->removeProduct($addCartData['product_class_id']);
  333.                 foreach ($result->getErrors() as $error) {
  334.                     $errorMessages[] = $error->getMessage();
  335.                 }
  336.             }
  337.             foreach ($result->getWarning() as $warning) {
  338.                 $errorMessages[] = $warning->getMessage();
  339.             }
  340.         }
  341.         $this->cartService->save();
  342.         log_info(
  343.             'カート追加処理完了',
  344.             [
  345.                 'product_id' => $Product->getId(),
  346.                 'product_class_id' => $addCartData['product_class_id'],
  347.                 'quantity' => $addCartData['quantity'],
  348.             ]
  349.         );
  350.         $event = new EventArgs(
  351.             [
  352.                 'form' => $form,
  353.                 'Product' => $Product,
  354.             ],
  355.             $request
  356.         );
  357.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE);
  358.         if ($event->getResponse() !== null) {
  359.             return $event->getResponse();
  360.         }
  361.         if ($request->isXmlHttpRequest()) {
  362.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  363.             // 初期化
  364.             $messages = [];
  365.             if (empty($errorMessages)) {
  366.                 // エラーが発生していない場合
  367.                 $done true;
  368.                 array_push($messagestrans('front.product.add_cart_complete'));
  369.             } else {
  370.                 // エラーが発生している場合
  371.                 $done false;
  372.                 $messages $errorMessages;
  373.             }
  374.             return $this->json(['done' => $done'messages' => $messages]);
  375.         } else {
  376.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  377.             foreach ($errorMessages as $errorMessage) {
  378.                 $this->addRequestError($errorMessage);
  379.             }
  380.             return $this->redirectToRoute('cart');
  381.         }
  382.     }
  383.     /**
  384.      * ページタイトルの設定
  385.      *
  386.      * @param  array|null $searchData
  387.      *
  388.      * @return str
  389.      */
  390.     protected function getPageTitle($searchData)
  391.     {
  392.         if (isset($searchData['name']) && !empty($searchData['name'])) {
  393.             return trans('front.product.search_result');
  394.         } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
  395.             return $searchData['category_id']->getName();
  396.         } else {
  397.             return trans('front.product.all_products');
  398.         }
  399.     }
  400.     /**
  401.      * 閲覧可能な商品かどうかを判定
  402.      *
  403.      * @param Product $Product
  404.      *
  405.      * @return boolean 閲覧可能な場合はtrue
  406.      */
  407.     protected function checkVisibility(Product $Product)
  408.     {
  409.         $is_admin $this->session->has('_security_admin');
  410.         // 管理ユーザの場合はステータスやオプションにかかわらず閲覧可能.
  411.         if (!$is_admin) {
  412.             // 在庫なし商品の非表示オプションが有効な場合.
  413.             // if ($this->BaseInfo->isOptionNostockHidden()) {
  414.             //     if (!$Product->getStockFind()) {
  415.             //         return false;
  416.             //     }
  417.             // }
  418.             // 公開ステータスでない商品は表示しない.
  419.             if ($Product->getStatus()->getId() !== ProductStatus::DISPLAY_SHOW) {
  420.                 return false;
  421.             }
  422.         }
  423.         return true;
  424.     }
  425. }