app/Customize/Controller/CustomProductController.php line 219

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