app/Customize/Controller/ProductController.php line 117

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\Controller\AbstractController;
  14. use Eccube\Entity\BaseInfo;
  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\Master\ProductListMaxType;
  21. use Eccube\Form\Type\Master\ProductListOrderByType;
  22. use Eccube\Form\Type\SearchProductType;
  23. use Eccube\Repository\BaseInfoRepository;
  24. use Eccube\Repository\CustomerFavoriteProductRepository;
  25. use Eccube\Repository\Master\ProductListMaxRepository;
  26. use Customize\Repository\ProductRepository;
  27. use Eccube\Service\CartService;
  28. use Eccube\Service\PurchaseFlow\PurchaseContext;
  29. use Eccube\Service\PurchaseFlow\PurchaseFlow;
  30. use Knp\Bundle\PaginatorBundle\Pagination\SlidingPagination;
  31. use Knp\Component\Pager\Paginator;
  32. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  33. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  34. use Symfony\Component\HttpFoundation\Request;
  35. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  36. use Symfony\Component\Routing\Annotation\Route;
  37. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  38. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  39. class ProductController extends AbstractController
  40. {
  41.     /**
  42.      * @var PurchaseFlow
  43.      */
  44.     protected $purchaseFlow;
  45.     /**
  46.      * @var CustomerFavoriteProductRepository
  47.      */
  48.     protected $customerFavoriteProductRepository;
  49.     /**
  50.      * @var CartService
  51.      */
  52.     protected $cartService;
  53.     /**
  54.      * @var ProductRepository
  55.      */
  56.     protected $productRepository;
  57.     /**
  58.      * @var BaseInfo
  59.      */
  60.     protected $BaseInfo;
  61.     /**
  62.      * @var AuthenticationUtils
  63.      */
  64.     protected $helper;
  65.     /**
  66.      * @var ProductListMaxRepository
  67.      */
  68.     protected $productListMaxRepository;
  69.     private $title '';
  70.     /**
  71.      * ProductController constructor.
  72.      *
  73.      * @param PurchaseFlow $cartPurchaseFlow
  74.      * @param CustomerFavoriteProductRepository $customerFavoriteProductRepository
  75.      * @param CartService $cartService
  76.      * @param ProductRepository $productRepository
  77.      * @param BaseInfoRepository $baseInfoRepository
  78.      * @param AuthenticationUtils $helper
  79.      * @param ProductListMaxRepository $productListMaxRepository
  80.      */
  81.     public function __construct(
  82.         PurchaseFlow $cartPurchaseFlow,
  83.         CustomerFavoriteProductRepository $customerFavoriteProductRepository,
  84.         CartService $cartService,
  85.         ProductRepository $productRepository,
  86.         BaseInfoRepository $baseInfoRepository,
  87.         AuthenticationUtils $helper,
  88.         ProductListMaxRepository $productListMaxRepository
  89.     ) {
  90.         $this->purchaseFlow $cartPurchaseFlow;
  91.         $this->customerFavoriteProductRepository $customerFavoriteProductRepository;
  92.         $this->cartService $cartService;
  93.         $this->productRepository $productRepository;
  94.         $this->BaseInfo $baseInfoRepository->get();
  95.         $this->helper $helper;
  96.         $this->productListMaxRepository $productListMaxRepository;
  97.     }
  98.     /**
  99.      * 商品一覧画面.
  100.      *
  101.      * @Route("/products/list", name="product_list")
  102.      * @Template("Product/list.twig")
  103.      */
  104.     public function index(Request $requestPaginator $paginator)
  105.     {
  106.         // カタログIDを取得
  107.         $cid $request->query->get('cid'0);
  108.         $this->session->set('cid',$cid); // セッションに保存
  109.         // Doctrine SQLFilter
  110.         if ($this->BaseInfo->isOptionNostockHidden()) {
  111.             $this->entityManager->getFilters()->enable('option_nostock_hidden');
  112.         }
  113.         // handleRequestは空のqueryの場合は無視するため
  114.         if ($request->getMethod() === 'GET') {
  115.             $request->query->set('pageno'$request->query->get('pageno'''));
  116.         }
  117.         // searchForm
  118.         /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  119.         $builder $this->formFactory->createNamedBuilder(''SearchProductType::class);
  120.         if ($request->getMethod() === 'GET') {
  121.             $builder->setMethod('GET');
  122.         }
  123.         $event = new EventArgs(
  124.             [
  125.                 'builder' => $builder,
  126.             ],
  127.             $request
  128.         );
  129.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_INDEX_INITIALIZE$event);
  130.         /* @var $searchForm \Symfony\Component\Form\FormInterface */
  131.         $searchForm $builder->getForm();
  132.         $searchForm->handleRequest($request);
  133.         // paginator
  134.         $searchData $searchForm->getData();
  135.         $searchData['cid'] = $cid;
  136.         $searchData['orderby'] = '';
  137.         $qb $this->productRepository->getQueryBuilderBySearchData($searchData);
  138.         $event = new EventArgs(
  139.             [
  140.                 'searchData' => $searchData,
  141.                 'qb' => $qb,
  142.             ],
  143.             $request
  144.         );
  145.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_INDEX_SEARCH$event);
  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.         // 表示件数
  177.         $builder $this->formFactory->createNamedBuilder(
  178.             'disp_number',
  179.             ProductListMaxType::class,
  180.             null,
  181.             [
  182.                 'required' => false,
  183.                 'allow_extra_fields' => true,
  184.             ]
  185.         );
  186.         if ($request->getMethod() === 'GET') {
  187.             $builder->setMethod('GET');
  188.         }
  189.         $event = new EventArgs(
  190.             [
  191.                 'builder' => $builder,
  192.             ],
  193.             $request
  194.         );
  195.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_INDEX_DISP$event);
  196.         $dispNumberForm $builder->getForm();
  197.         $dispNumberForm->handleRequest($request);
  198.         // ソート順
  199.         $builder $this->formFactory->createNamedBuilder(
  200.             'orderby',
  201.             ProductListOrderByType::class,
  202.             null,
  203.             [
  204.                 'required' => false,
  205.                 'allow_extra_fields' => true,
  206.             ]
  207.         );
  208.         if ($request->getMethod() === 'GET') {
  209.             $builder->setMethod('GET');
  210.         }
  211.         $event = new EventArgs(
  212.             [
  213.                 'builder' => $builder,
  214.             ],
  215.             $request
  216.         );
  217.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_INDEX_ORDER$event);
  218.         $orderByForm $builder->getForm();
  219.         $orderByForm->handleRequest($request);
  220.         $Category $searchForm->get('category_id')->getData();
  221.         return [
  222.             'subtitle' => $this->getPageTitle($searchData),
  223.             'pagination' => $pagination,
  224.             'search_form' => $searchForm->createView(),
  225.             'disp_number_form' => $dispNumberForm->createView(),
  226.             'order_by_form' => $orderByForm->createView(),
  227.             'forms' => $forms,
  228.             'Category' => $Category,
  229.             'cid' => $cid,
  230.         ];
  231.     }
  232.     /**
  233.      * 商品詳細画面.
  234.      *
  235.      * @Route("/products/detail/{id}", name="product_detail", methods={"GET"}, requirements={"id" = "\d+"})
  236.      * @Template("Product/detail.twig")
  237.      * @ParamConverter("Product", options={"repository_method" = "findWithSortedClassCategories"})
  238.      *
  239.      * @param Request $request
  240.      * @param Product $Product
  241.      *
  242.      * @return array
  243.      */
  244.     public function detail(Request $requestProduct $Product)
  245.     {
  246.         if (!$this->checkVisibility($Product)) {
  247.             throw new NotFoundHttpException();
  248.         }
  249.         $builder $this->formFactory->createNamedBuilder(
  250.             '',
  251.             AddCartType::class,
  252.             null,
  253.             [
  254.                 'product' => $Product,
  255.                 'id_add_product_id' => false,
  256.             ]
  257.         );
  258.         $event = new EventArgs(
  259.             [
  260.                 'builder' => $builder,
  261.                 'Product' => $Product,
  262.             ],
  263.             $request
  264.         );
  265.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE$event);
  266.         $is_favorite false;
  267.         if ($this->isGranted('ROLE_USER')) {
  268.             $Customer $this->getUser();
  269.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  270.         }
  271.         return [
  272.             'title' => $this->title,
  273.             'subtitle' => $Product->getName(),
  274.             'form' => $builder->getForm()->createView(),
  275.             'Product' => $Product,
  276.             'is_favorite' => $is_favorite,
  277.         ];
  278.     }
  279.     /**
  280.      * お気に入り追加.
  281.      *
  282.      * @Route("/products/add_favorite/{id}", name="product_add_favorite", requirements={"id" = "\d+"})
  283.      */
  284.     public function addFavorite(Request $requestProduct $Product)
  285.     {
  286.         $this->checkVisibility($Product);
  287.         $event = new EventArgs(
  288.             [
  289.                 'Product' => $Product,
  290.             ],
  291.             $request
  292.         );
  293.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_INITIALIZE$event);
  294.         if ($this->isGranted('ROLE_USER')) {
  295.             $Customer $this->getUser();
  296.             $this->customerFavoriteProductRepository->addFavorite($Customer$Product);
  297.             $this->session->getFlashBag()->set('product_detail.just_added_favorite'$Product->getId());
  298.             $event = new EventArgs(
  299.                 [
  300.                     'Product' => $Product,
  301.                 ],
  302.                 $request
  303.             );
  304.             $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE$event);
  305.             return $this->redirectToRoute('product_detail', ['id' => $Product->getId()]);
  306.         } else {
  307.             // 非会員の場合、ログイン画面を表示
  308.             //  ログイン後の画面遷移先を設定
  309.             $this->setLoginTargetPath($this->generateUrl('product_add_favorite', ['id' => $Product->getId()], UrlGeneratorInterface::ABSOLUTE_URL));
  310.             $this->session->getFlashBag()->set('eccube.add.favorite'true);
  311.             $event = new EventArgs(
  312.                 [
  313.                     'Product' => $Product,
  314.                 ],
  315.                 $request
  316.             );
  317.             $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE$event);
  318.             return $this->redirectToRoute('mypage_login');
  319.         }
  320.     }
  321.     /**
  322.      * カートに追加.
  323.      *
  324.      * @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
  325.      */
  326.     public function addCart(Request $requestProduct $Product)
  327.     {
  328.         // エラーメッセージの配列
  329.         $errorMessages = [];
  330.         if (!$this->checkVisibility($Product)) {
  331.             throw new NotFoundHttpException();
  332.         }
  333.         $builder $this->formFactory->createNamedBuilder(
  334.             '',
  335.             AddCartType::class,
  336.             null,
  337.             [
  338.                 'product' => $Product,
  339.                 'id_add_product_id' => false,
  340.             ]
  341.         );
  342.         $event = new EventArgs(
  343.             [
  344.                 'builder' => $builder,
  345.                 'Product' => $Product,
  346.             ],
  347.             $request
  348.         );
  349.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE$event);
  350.         /* @var $form \Symfony\Component\Form\FormInterface */
  351.         $form $builder->getForm();
  352.         $form->handleRequest($request);
  353.         if (!$form->isValid()) {
  354.             throw new NotFoundHttpException();
  355.         }
  356.         $addCartData $form->getData();
  357.         log_info(
  358.             'カート追加処理開始',
  359.             [
  360.                 'product_id' => $Product->getId(),
  361.                 'product_class_id' => $addCartData['product_class_id'],
  362.                 'quantity' => $addCartData['quantity'],
  363.             ]
  364.         );
  365.         // カートへ追加
  366.         $this->cartService->addProduct($addCartData['product_class_id'], $addCartData['quantity']);
  367.         // 明細の正規化
  368.         $Carts $this->cartService->getCarts();
  369.         foreach ($Carts as $Cart) {
  370.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  371.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  372.             if ($result->hasError()) {
  373.                 $this->cartService->removeProduct($addCartData['product_class_id']);
  374.                 foreach ($result->getErrors() as $error) {
  375.                     $errorMessages[] = $error->getMessage();
  376.                 }
  377.             }
  378.             foreach ($result->getWarning() as $warning) {
  379.                 $errorMessages[] = $warning->getMessage();
  380.             }
  381.         }
  382.         $this->cartService->save();
  383.         log_info(
  384.             'カート追加処理完了',
  385.             [
  386.                 'product_id' => $Product->getId(),
  387.                 'product_class_id' => $addCartData['product_class_id'],
  388.                 'quantity' => $addCartData['quantity'],
  389.             ]
  390.         );
  391.         $event = new EventArgs(
  392.             [
  393.                 'form' => $form,
  394.                 'Product' => $Product,
  395.             ],
  396.             $request
  397.         );
  398.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE$event);
  399.         if ($event->getResponse() !== null) {
  400.             return $event->getResponse();
  401.         }
  402.         if ($request->isXmlHttpRequest()) {
  403.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  404.             // 初期化
  405.             $done null;
  406.             $messages = [];
  407.             if (empty($errorMessages)) {
  408.                 // エラーが発生していない場合
  409.                 $done true;
  410.                 array_push($messagestrans('front.product.add_cart_complete'));
  411.             } else {
  412.                 // エラーが発生している場合
  413.                 $done false;
  414.                 $messages $errorMessages;
  415.             }
  416.             return $this->json(['done' => $done'messages' => $messages]);
  417.         } else {
  418.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  419.             foreach ($errorMessages as $errorMessage) {
  420.                 $this->addRequestError($errorMessage);
  421.             }
  422.             return $this->redirectToRoute('cart');
  423.         }
  424.     }
  425.     /**
  426.      * ページタイトルの設定
  427.      *
  428.      * @param  null|array $searchData
  429.      *
  430.      * @return str
  431.      */
  432.     protected function getPageTitle($searchData)
  433.     {
  434.         if (isset($searchData['name']) && !empty($searchData['name'])) {
  435.             return trans('front.product.search_result');
  436.         } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
  437.             return $searchData['category_id']->getName();
  438.         } else {
  439.             return trans('front.product.all_products');
  440.         }
  441.     }
  442.     /**
  443.      * 閲覧可能な商品かどうかを判定
  444.      *
  445.      * @param Product $Product
  446.      *
  447.      * @return boolean 閲覧可能な場合はtrue
  448.      */
  449.     protected function checkVisibility(Product $Product)
  450.     {
  451.         $is_admin $this->session->has('_security_admin');
  452.         // 管理ユーザの場合はステータスやオプションにかかわらず閲覧可能.
  453.         if (!$is_admin) {
  454.             // 在庫なし商品の非表示オプションが有効な場合.
  455.             // if ($this->BaseInfo->isOptionNostockHidden()) {
  456.             //     if (!$Product->getStockFind()) {
  457.             //         return false;
  458.             //     }
  459.             // }
  460.             // 公開ステータスでない商品は表示しない.
  461.             if ($Product->getStatus()->getId() !== ProductStatus::DISPLAY_SHOW) {
  462.                 return false;
  463.             }
  464.         }
  465.         return true;
  466.     }
  467. }