src/Eccube/Controller/ProductController.php line 40

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