app/Customize/Controller/CustomProductController.php line 154

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. use Customize\Repository\CustomProductRepository;
  38. class CustomProductController extends AbstractController
  39. {
  40.     /**
  41.      * @var PurchaseFlow
  42.      */
  43.     protected $purchaseFlow;
  44.     /**
  45.      * @var CustomerFavoriteProductRepository
  46.      */
  47.     protected $customerFavoriteProductRepository;
  48.     /**
  49.      * @var CartService
  50.      */
  51.     protected $cartService;
  52.     /**
  53.      * @var ProductRepository
  54.      */
  55.     protected $productRepository;
  56.     /**
  57.      * @var BaseInfo
  58.      */
  59.     protected $BaseInfo;
  60.     /**
  61.      * @var AuthenticationUtils
  62.      */
  63.     protected $helper;
  64.     /**
  65.      * @var ProductListMaxRepository
  66.      */
  67.     protected $productListMaxRepository;
  68.     /**
  69.      * @var CustomProductRepository
  70.      */
  71.     protected $customProductRepository;
  72.     private $title '';
  73.     /**
  74.      * ProductController constructor.
  75.      *
  76.      * @param PurchaseFlow $cartPurchaseFlow
  77.      * @param CustomerFavoriteProductRepository $customerFavoriteProductRepository
  78.      * @param CartService $cartService
  79.      * @param ProductRepository $productRepository
  80.      * @param BaseInfoRepository $baseInfoRepository
  81.      * @param AuthenticationUtils $helper
  82.      * @param ProductListMaxRepository $productListMaxRepository
  83.      */
  84.     public function __construct(
  85.         PurchaseFlow $cartPurchaseFlow,
  86.         CustomerFavoriteProductRepository $customerFavoriteProductRepository,
  87.         CartService $cartService,
  88.         ProductRepository $productRepository,
  89.         BaseInfoRepository $baseInfoRepository,
  90.         AuthenticationUtils $helper,
  91.         ProductListMaxRepository $productListMaxRepository,
  92.         CustomProductRepository $customProductRepository
  93.     ) {
  94.         $this->purchaseFlow $cartPurchaseFlow;
  95.         $this->customerFavoriteProductRepository $customerFavoriteProductRepository;
  96.         $this->cartService $cartService;
  97.         $this->productRepository $productRepository;
  98.         $this->BaseInfo $baseInfoRepository->get();
  99.         $this->helper $helper;
  100.         $this->productListMaxRepository $productListMaxRepository;
  101.         $this->customProductRepository $customProductRepository;
  102.     }
  103.     /**
  104.      * 商品一覧画面.
  105.      *
  106.      * @Route("/products", name="product_list", methods={"GET"})
  107.      * @Template("Product/list.twig")
  108.      */
  109.     public function index(Request $requestPaginatorInterface $paginator)
  110.     {
  111.         // Doctrine SQLFilter
  112.         if ($this->BaseInfo->isOptionNostockHidden()) {
  113.             $this->entityManager->getFilters()->enable('option_nostock_hidden');
  114.         }
  115.         // handleRequestは空のqueryの場合は無視するため
  116.         if ($request->getMethod() === 'GET') {
  117.             $request->query->set('pageno'$request->query->get('pageno'''));
  118.         }
  119.         // searchForm
  120.         /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  121.         $builder $this->formFactory->createNamedBuilder(''SearchProductType::class);
  122.         if ($request->getMethod() === 'GET') {
  123.             $builder->setMethod('GET');
  124.         }
  125.         $event = new EventArgs(
  126.             [
  127.                 'builder' => $builder,
  128.             ],
  129.             $request
  130.         );
  131.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_INITIALIZE);
  132.         /* @var $searchForm \Symfony\Component\Form\FormInterface */
  133.         $searchForm $builder->getForm();
  134.         $searchForm->handleRequest($request);
  135.         // paginator
  136.         $searchData $searchForm->getData();
  137.         $qb $this->customProductRepository->customGetQueryBuilderBySearchData($searchData);
  138.         $event = new EventArgs(
  139.             [
  140.                 'searchData' => $searchData,
  141.                 'qb' => $qb,
  142.             ],
  143.             $request
  144.         );
  145.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_SEARCH);
  146.         $searchData $event->getArgument('searchData');
  147.         $query $qb->getQuery()
  148.             ->useResultCache(true$this->eccubeConfig['eccube_result_cache_lifetime_short']);
  149.         /** @var SlidingPagination $pagination */
  150.         $pagination $paginator->paginate(
  151.             $query,
  152.             !empty($searchData['pageno']) ? $searchData['pageno'] : 1,
  153.             !empty($searchData['disp_number']) ? $searchData['disp_number']->getId() : $this->productListMaxRepository->findOneBy([], ['sort_no' => 'ASC'])->getId()
  154.         );
  155.         $ids = [];
  156.         foreach ($pagination as $Product) {
  157.             $ids[] = $Product->getId();
  158.         }
  159.         $ProductsAndClassCategories $this->productRepository->findProductsWithSortedClassCategories($ids'p.id');
  160.         // addCart form
  161.         $forms = [];
  162.         foreach ($pagination as $Product) {
  163.             /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  164.             $builder $this->formFactory->createNamedBuilder(
  165.                 '',
  166.                 AddCartType::class,
  167.                 null,
  168.                 [
  169.                     'product' => $ProductsAndClassCategories[$Product->getId()],
  170.                     'allow_extra_fields' => true,
  171.                 ]
  172.             );
  173.             $addCartForm $builder->getForm();
  174.             $forms[$Product->getId()] = $addCartForm->createView();
  175.         }
  176.         $Category $searchForm->get('category_id')->getData();
  177.         return [
  178.             'subtitle' => $this->getPageTitle($searchData),
  179.             'pagination' => $pagination,
  180.             'search_form' => $searchForm->createView(),
  181.             'forms' => $forms,
  182.             'Category' => $Category,
  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.         return [
  225.             'title' => $this->title,
  226.             'subtitle' => $Product->getName(),
  227.             'form' => $builder->getForm()->createView(),
  228.             'Product' => $Product,
  229.             'is_favorite' => $is_favorite,
  230.         ];
  231.     }
  232.     /**
  233.      * お気に入り追加.
  234.      *
  235.      * @Route("/products/add_favorite/{id}", name="product_add_favorite", requirements={"id" = "\d+"}, methods={"GET", "POST"})
  236.      */
  237.     public function addFavorite(Request $requestProduct $Product)
  238.     {
  239.         $this->checkVisibility($Product);
  240.         $event = new EventArgs(
  241.             [
  242.                 'Product' => $Product,
  243.             ],
  244.             $request
  245.         );
  246.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_INITIALIZE);
  247.         if ($this->isGranted('ROLE_USER')) {
  248.             $Customer $this->getUser();
  249.             $this->customerFavoriteProductRepository->addFavorite($Customer$Product);
  250.             $this->session->getFlashBag()->set('product_detail.just_added_favorite'$Product->getId());
  251.             $event = new EventArgs(
  252.                 [
  253.                     'Product' => $Product,
  254.                 ],
  255.                 $request
  256.             );
  257.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  258.             return $this->redirectToRoute('product_detail', ['id' => $Product->getId()]);
  259.         } else {
  260.             // 非会員の場合、ログイン画面を表示
  261.             //  ログイン後の画面遷移先を設定
  262.             $this->setLoginTargetPath($this->generateUrl('product_add_favorite', ['id' => $Product->getId()], UrlGeneratorInterface::ABSOLUTE_URL));
  263.             $this->session->getFlashBag()->set('eccube.add.favorite'true);
  264.             $event = new EventArgs(
  265.                 [
  266.                     'Product' => $Product,
  267.                 ],
  268.                 $request
  269.             );
  270.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  271.             return $this->redirectToRoute('mypage_login');
  272.         }
  273.     }
  274.     /**
  275.      * カートに追加.
  276.      *
  277.      * @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
  278.      */
  279.     public function addCart(Request $requestProduct $Product)
  280.     {
  281.         // エラーメッセージの配列
  282.         $errorMessages = [];
  283.         if (!$this->checkVisibility($Product)) {
  284.             throw new NotFoundHttpException();
  285.         }
  286.         $builder $this->formFactory->createNamedBuilder(
  287.             '',
  288.             AddCartType::class,
  289.             null,
  290.             [
  291.                 'product' => $Product,
  292.                 'id_add_product_id' => false,
  293.             ]
  294.         );
  295.         $event = new EventArgs(
  296.             [
  297.                 'builder' => $builder,
  298.                 'Product' => $Product,
  299.             ],
  300.             $request
  301.         );
  302.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE);
  303.         /* @var $form \Symfony\Component\Form\FormInterface */
  304.         $form $builder->getForm();
  305.         $form->handleRequest($request);
  306.         if (!$form->isValid()) {
  307.             throw new NotFoundHttpException();
  308.         }
  309.         $addCartData $form->getData();
  310.         log_info(
  311.             'カート追加処理開始',
  312.             [
  313.                 'product_id' => $Product->getId(),
  314.                 'product_class_id' => $addCartData['product_class_id'],
  315.                 'quantity' => $addCartData['quantity'],
  316.             ]
  317.         );
  318.         // カートへ追加
  319.         $this->cartService->addProduct($addCartData['product_class_id'], $addCartData['quantity']);
  320.         // 明細の正規化
  321.         $Carts $this->cartService->getCarts();
  322.         foreach ($Carts as $Cart) {
  323.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  324.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  325.             if ($result->hasError()) {
  326.                 $this->cartService->removeProduct($addCartData['product_class_id']);
  327.                 foreach ($result->getErrors() as $error) {
  328.                     $errorMessages[] = $error->getMessage();
  329.                 }
  330.             }
  331.             foreach ($result->getWarning() as $warning) {
  332.                 $errorMessages[] = $warning->getMessage();
  333.             }
  334.         }
  335.         $this->cartService->save();
  336.         log_info(
  337.             'カート追加処理完了',
  338.             [
  339.                 'product_id' => $Product->getId(),
  340.                 'product_class_id' => $addCartData['product_class_id'],
  341.                 'quantity' => $addCartData['quantity'],
  342.             ]
  343.         );
  344.         $event = new EventArgs(
  345.             [
  346.                 'form' => $form,
  347.                 'Product' => $Product,
  348.             ],
  349.             $request
  350.         );
  351.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE);
  352.         if ($event->getResponse() !== null) {
  353.             return $event->getResponse();
  354.         }
  355.         if ($request->isXmlHttpRequest()) {
  356.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  357.             // 初期化
  358.             $messages = [];
  359.             if (empty($errorMessages)) {
  360.                 // エラーが発生していない場合
  361.                 $done true;
  362.                 array_push($messagestrans('front.product.add_cart_complete'));
  363.             } else {
  364.                 // エラーが発生している場合
  365.                 $done false;
  366.                 $messages $errorMessages;
  367.             }
  368.             return $this->json(['done' => $done'messages' => $messages]);
  369.         } else {
  370.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  371.             foreach ($errorMessages as $errorMessage) {
  372.                 $this->addRequestError($errorMessage);
  373.             }
  374.             return $this->redirectToRoute('cart');
  375.         }
  376.     }
  377.     /**
  378.      * ページタイトルの設定
  379.      *
  380.      * @param  array|null $searchData
  381.      *
  382.      * @return str
  383.      */
  384.     protected function getPageTitle($searchData)
  385.     {
  386.         if (isset($searchData['name']) && !empty($searchData['name'])) {
  387.             return trans('front.product.search_result');
  388.         } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
  389.             return $searchData['category_id']->getName();
  390.         } else {
  391.             return trans('front.product.all_products');
  392.         }
  393.     }
  394.     /**
  395.      * 閲覧可能な商品かどうかを判定
  396.      *
  397.      * @param Product $Product
  398.      *
  399.      * @return boolean 閲覧可能な場合はtrue
  400.      */
  401.     protected function checkVisibility(Product $Product)
  402.     {
  403.         $is_admin $this->session->has('_security_admin');
  404.         // 管理ユーザの場合はステータスやオプションにかかわらず閲覧可能.
  405.         if (!$is_admin) {
  406.             // 在庫なし商品の非表示オプションが有効な場合.
  407.             // if ($this->BaseInfo->isOptionNostockHidden()) {
  408.             //     if (!$Product->getStockFind()) {
  409.             //         return false;
  410.             //     }
  411.             // }
  412.             // 公開ステータスでない商品は表示しない.
  413.             if ($Product->getStatus()->getId() !== ProductStatus::DISPLAY_SHOW) {
  414.                 return false;
  415.             }
  416.         }
  417.         return true;
  418.     }
  419. }