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