app/Customize/Controller/CustomProductController.php line 564

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 Customize\Repository\CustomizeProductRepository;
  14. use Eccube\Controller\AbstractController;
  15. use Eccube\Entity\BaseInfo;
  16. use Eccube\Entity\Master\ProductStatus;
  17. use Eccube\Entity\Product;
  18. use Eccube\Event\EccubeEvents;
  19. use Eccube\Event\EventArgs;
  20. use Eccube\Form\Type\AddCartType;
  21. use Eccube\Form\Type\SearchProductType;
  22. use Eccube\Repository\BaseInfoRepository;
  23. use Eccube\Repository\CustomerFavoriteProductRepository;
  24. use Eccube\Repository\Master\ProductListMaxRepository;
  25. use Eccube\Repository\ProductRepository;
  26. use Eccube\Service\CartService;
  27. use Eccube\Service\PurchaseFlow\PurchaseContext;
  28. use Eccube\Service\PurchaseFlow\PurchaseFlow;
  29. use Knp\Bundle\PaginatorBundle\Pagination\SlidingPagination;
  30. use Knp\Component\Pager\PaginatorInterface;
  31. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  32. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  33. use Symfony\Component\HttpFoundation\Request;
  34. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  35. use Symfony\Component\Routing\Annotation\Route;
  36. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  37. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  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.     protected $customizeProductRepository;
  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.      * @param CustomizeProductRepository $productRepository
  81.      */
  82.     public function __construct(
  83.         PurchaseFlow $cartPurchaseFlow,
  84.         CustomerFavoriteProductRepository $customerFavoriteProductRepository,
  85.         CartService $cartService,
  86.         ProductRepository $productRepository,
  87.         BaseInfoRepository $baseInfoRepository,
  88.         AuthenticationUtils $helper,
  89.         ProductListMaxRepository $productListMaxRepository,
  90.         CustomizeProductRepository $customizeProductRepository
  91.     ) {
  92.         $this->purchaseFlow $cartPurchaseFlow;
  93.         $this->customerFavoriteProductRepository $customerFavoriteProductRepository;
  94.         $this->cartService $cartService;
  95.         $this->productRepository $productRepository;
  96.         $this->BaseInfo $baseInfoRepository->get();
  97.         $this->helper $helper;
  98.         $this->productListMaxRepository $productListMaxRepository;
  99.         $this->customizeProductRepository $customizeProductRepository;
  100.     }
  101.     /**
  102.      * 商品一覧画面.
  103.      *
  104.      * @Route("/products/list", name="product_list", methods={"GET"})
  105.      * @Template("Product/list.twig")
  106.      */
  107.     public function index(Request $requestPaginatorInterface $paginator)
  108.     {
  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($eventEccubeEvents::FRONT_PRODUCT_INDEX_INITIALIZE);
  130.         /* @var $searchForm \Symfony\Component\Form\FormInterface */
  131.         $searchForm $builder->getForm();
  132.         $searchForm->handleRequest($request);
  133.         // paginator
  134.         $searchData $searchForm->getData();
  135.         $qb $this->productRepository->getQueryBuilderBySearchData($searchData);
  136.         $event = new EventArgs(
  137.             [
  138.                 'searchData' => $searchData,
  139.                 'qb' => $qb,
  140.             ],
  141.             $request
  142.         );
  143.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_SEARCH);
  144.         $searchData $event->getArgument('searchData');
  145.         $query $qb->getQuery()
  146.             ->useResultCache(true$this->eccubeConfig['eccube_result_cache_lifetime_short']);
  147.         /** @var SlidingPagination $pagination */
  148.         $pagination $paginator->paginate(
  149.             $query,
  150.             !empty($searchData['pageno']) ? $searchData['pageno'] : 1,
  151.             !empty($searchData['disp_number']) ? $searchData['disp_number']->getId() : $this->productListMaxRepository->findOneBy([], ['sort_no' => 'ASC'])->getId()
  152.         );
  153.         $ids = [];
  154.         foreach ($pagination as $Product) {
  155.             $ids[] = $Product->getId();
  156.         }
  157.         $ProductsAndClassCategories $this->productRepository->findProductsWithSortedClassCategories($ids'p.id');
  158.         // addCart form
  159.         $forms = [];
  160.         foreach ($pagination as $Product) {
  161.             /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  162.             $builder $this->formFactory->createNamedBuilder(
  163.                 '',
  164.                 AddCartType::class,
  165.                 null,
  166.                 [
  167.                     'product' => $ProductsAndClassCategories[$Product->getId()],
  168.                     'allow_extra_fields' => true,
  169.                 ]
  170.             );
  171.             $addCartForm $builder->getForm();
  172.             $forms[$Product->getId()] = $addCartForm->createView();
  173.         }
  174.         $Category $searchForm->get('category_id')->getData();
  175.         return [
  176.             'subtitle' => $this->getPageTitle($searchData),
  177.             'pagination' => $pagination,
  178.             'search_form' => $searchForm->createView(),
  179.             'forms' => $forms,
  180.             'Category' => $Category,
  181.         ];
  182.     }
  183.     
  184.     /**
  185.      * 商品一覧画面チェック.
  186.      *
  187.      * @Route("/products/list_check", name="product_list_check", methods={"GET"})
  188.      * @Template("Product/list_check.twig")
  189.      */
  190.     public function listcheck(Request $requestPaginatorInterface $paginator)
  191.     {
  192.         // Doctrine SQLFilter
  193.         if ($this->BaseInfo->isOptionNostockHidden()) {
  194.             $this->entityManager->getFilters()->enable('option_nostock_hidden');
  195.         }
  196.         // handleRequestは空のqueryの場合は無視するため
  197.         if ($request->getMethod() === 'GET') {
  198.             $request->query->set('pageno'$request->query->get('pageno'''));
  199.         }
  200.         // searchForm
  201.         /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  202.         $builder $this->formFactory->createNamedBuilder(''SearchProductType::class);
  203.         if ($request->getMethod() === 'GET') {
  204.             $builder->setMethod('GET');
  205.         }
  206.         $event = new EventArgs(
  207.             [
  208.                 'builder' => $builder,
  209.             ],
  210.             $request
  211.         );
  212.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_INITIALIZE);
  213.         /* @var $searchForm \Symfony\Component\Form\FormInterface */
  214.         $searchForm $builder->getForm();
  215.         $searchForm->handleRequest($request);
  216.         // paginator
  217.         $searchData $searchForm->getData();
  218.         $qb $this->productRepository->getQueryBuilderBySearchData($searchData);
  219.         $event = new EventArgs(
  220.             [
  221.                 'searchData' => $searchData,
  222.                 'qb' => $qb,
  223.             ],
  224.             $request
  225.         );
  226.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_SEARCH);
  227.         $searchData $event->getArgument('searchData');
  228.         $query $qb->getQuery()
  229.             ->useResultCache(true$this->eccubeConfig['eccube_result_cache_lifetime_short']);
  230.         /** @var SlidingPagination $pagination */
  231.         $pagination $paginator->paginate(
  232.             $query,
  233.             !empty($searchData['pageno']) ? $searchData['pageno'] : 1,
  234.             !empty($searchData['disp_number']) ? $searchData['disp_number']->getId() : $this->productListMaxRepository->findOneBy([], ['sort_no' => 'ASC'])->getId()
  235.         );
  236.         $ids = [];
  237.         foreach ($pagination as $Product) {
  238.             $ids[] = $Product->getId();
  239.         }
  240.         $ProductsAndClassCategories $this->productRepository->findProductsWithSortedClassCategories($ids'p.id');
  241.         // addCart form
  242.         $forms = [];
  243.         foreach ($pagination as $Product) {
  244.             /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  245.             $builder $this->formFactory->createNamedBuilder(
  246.                 '',
  247.                 AddCartType::class,
  248.                 null,
  249.                 [
  250.                     'product' => $ProductsAndClassCategories[$Product->getId()],
  251.                     'allow_extra_fields' => true,
  252.                 ]
  253.             );
  254.             $addCartForm $builder->getForm();
  255.             $forms[$Product->getId()] = $addCartForm->createView();
  256.         }
  257.         $Category $searchForm->get('category_id')->getData();
  258.         return [
  259.             'subtitle' => $this->getPageTitle($searchData),
  260.             'pagination' => $pagination,
  261.             'search_form' => $searchForm->createView(),
  262.             'forms' => $forms,
  263.             'Category' => $Category,
  264.         ];
  265.     }
  266.     
  267.     /**
  268.      * 商品詳細画面.
  269.      *
  270.      * @Route("/products/detail/{id}", name="product_detail", methods={"GET"}, requirements={"id" = "\d+"})
  271.      * @Template("Product/detail.twig")
  272.      * @ParamConverter("Product", options={"repository_method" = "findWithSortedClassCategories"})
  273.      *
  274.      * @param Request $request
  275.      * @param Product $Product
  276.      *
  277.      * @return array
  278.      */
  279.     public function detail(Request $requestProduct $Product)
  280.     {
  281.         if (!$this->checkVisibility($Product)) {
  282.             throw new NotFoundHttpException();
  283.         }
  284.         $builder $this->formFactory->createNamedBuilder(
  285.             '',
  286.             AddCartType::class,
  287.             null,
  288.             [
  289.                 'product' => $Product,
  290.                 'id_add_product_id' => false,
  291.             ]
  292.         );
  293.         $event = new EventArgs(
  294.             [
  295.                 'builder' => $builder,
  296.                 'Product' => $Product,
  297.             ],
  298.             $request
  299.         );
  300.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE);
  301.         $is_favorite false;
  302.         if ($this->isGranted('ROLE_USER')) {
  303.             $Customer $this->getUser();
  304.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  305.         }
  306.         $Comparison $this->customizeProductRepository->Comparison();
  307.         return [
  308.             'title' => $this->title,
  309.             'subtitle' => $Product->getName(),
  310.             'form' => $builder->getForm()->createView(),
  311.             'Product' => $Product,
  312.             'is_favorite' => $is_favorite,
  313.             'Comparison' => $Comparison,
  314.         ];
  315.     }
  316.     /**
  317.      * お気に入り追加.
  318.      *
  319.      * @Route("/products/add_favorite/{id}", name="product_add_favorite", requirements={"id" = "\d+"}, methods={"GET", "POST"})
  320.      */
  321.     public function addFavorite(Request $requestProduct $Product)
  322.     {
  323.         $this->checkVisibility($Product);
  324.         $event = new EventArgs(
  325.             [
  326.                 'Product' => $Product,
  327.             ],
  328.             $request
  329.         );
  330.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_INITIALIZE);
  331.         if ($this->isGranted('ROLE_USER')) {
  332.             $Customer $this->getUser();
  333.             $this->customerFavoriteProductRepository->addFavorite($Customer$Product);
  334.             $this->session->getFlashBag()->set('product_detail.just_added_favorite'$Product->getId());
  335.             $event = new EventArgs(
  336.                 [
  337.                     'Product' => $Product,
  338.                 ],
  339.                 $request
  340.             );
  341.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  342.             return $this->redirectToRoute('product_detail', ['id' => $Product->getId()]);
  343.         } else {
  344.             // 非会員の場合、ログイン画面を表示
  345.             //  ログイン後の画面遷移先を設定
  346.             $this->setLoginTargetPath($this->generateUrl('product_add_favorite', ['id' => $Product->getId()], UrlGeneratorInterface::ABSOLUTE_URL));
  347.             $this->session->getFlashBag()->set('eccube.add.favorite'true);
  348.             $event = new EventArgs(
  349.                 [
  350.                     'Product' => $Product,
  351.                 ],
  352.                 $request
  353.             );
  354.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  355.             return $this->redirectToRoute('mypage_login');
  356.         }
  357.     }
  358.     /**
  359.      * カートに追加.
  360.      *
  361.      * @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
  362.      */
  363.     public function addCart(Request $requestProduct $Product)
  364.     {
  365.         // エラーメッセージの配列
  366.         $errorMessages = [];
  367.         if (!$this->checkVisibility($Product)) {
  368.             throw new NotFoundHttpException();
  369.         }
  370.         $builder $this->formFactory->createNamedBuilder(
  371.             '',
  372.             AddCartType::class,
  373.             null,
  374.             [
  375.                 'product' => $Product,
  376.                 'id_add_product_id' => false,
  377.             ]
  378.         );
  379.         $event = new EventArgs(
  380.             [
  381.                 'builder' => $builder,
  382.                 'Product' => $Product,
  383.             ],
  384.             $request
  385.         );
  386.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE);
  387.         /* @var $form \Symfony\Component\Form\FormInterface */
  388.         $form $builder->getForm();
  389.         $form->handleRequest($request);
  390.         if (!$form->isValid()) {
  391.             throw new NotFoundHttpException();
  392.         }
  393.         $addCartData $form->getData();
  394.         log_info(
  395.             'カート追加処理開始',
  396.             [
  397.                 'product_id' => $Product->getId(),
  398.                 'product_class_id' => $addCartData['product_class_id'],
  399.                 'quantity' => $addCartData['quantity'],
  400.             ]
  401.         );
  402.         // カートへ追加
  403.         $this->cartService->addProduct($addCartData['product_class_id'], $addCartData['quantity']);
  404.         // 明細の正規化
  405.         $Carts $this->cartService->getCarts();
  406.         foreach ($Carts as $Cart) {
  407.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  408.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  409.             if ($result->hasError()) {
  410.                 $this->cartService->removeProduct($addCartData['product_class_id']);
  411.                 foreach ($result->getErrors() as $error) {
  412.                     $errorMessages[] = $error->getMessage();
  413.                 }
  414.             }
  415.             foreach ($result->getWarning() as $warning) {
  416.                 $errorMessages[] = $warning->getMessage();
  417.             }
  418.         }
  419.         $this->cartService->save();
  420.         log_info(
  421.             'カート追加処理完了',
  422.             [
  423.                 'product_id' => $Product->getId(),
  424.                 'product_class_id' => $addCartData['product_class_id'],
  425.                 'quantity' => $addCartData['quantity'],
  426.             ]
  427.         );
  428.         $event = new EventArgs(
  429.             [
  430.                 'form' => $form,
  431.                 'Product' => $Product,
  432.             ],
  433.             $request
  434.         );
  435.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE);
  436.         if ($event->getResponse() !== null) {
  437.             return $event->getResponse();
  438.         }
  439.         if ($request->isXmlHttpRequest()) {
  440.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  441.             // 初期化
  442.             $messages = [];
  443.             if (empty($errorMessages)) {
  444.                 // エラーが発生していない場合
  445.                 $done true;
  446.                 array_push($messagestrans('front.product.add_cart_complete'));
  447.             } else {
  448.                 // エラーが発生している場合
  449.                 $done false;
  450.                 $messages $errorMessages;
  451.             }
  452.             return $this->json(['done' => $done'messages' => $messages]);
  453.         } else {
  454.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  455.             foreach ($errorMessages as $errorMessage) {
  456.                 $this->addRequestError($errorMessage);
  457.             }
  458.             return $this->redirectToRoute('cart');
  459.         }
  460.     }
  461.     /**
  462.      * ページタイトルの設定
  463.      *
  464.      * @param  array|null $searchData
  465.      *
  466.      * @return str
  467.      */
  468.     protected function getPageTitle($searchData)
  469.     {
  470.         if (isset($searchData['name']) && !empty($searchData['name'])) {
  471.             return trans('front.product.search_result');
  472.         } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
  473.             return $searchData['category_id']->getName();
  474.         } else {
  475.             return trans('front.product.all_products');
  476.         }
  477.     }
  478.     /**
  479.      * 閲覧可能な商品かどうかを判定
  480.      *
  481.      * @param Product $Product
  482.      *
  483.      * @return boolean 閲覧可能な場合はtrue
  484.      */
  485.     protected function checkVisibility(Product $Product)
  486.     {
  487.         $is_admin $this->session->has('_security_admin');
  488.         // 管理ユーザの場合はステータスやオプションにかかわらず閲覧可能.
  489.         if (!$is_admin) {
  490.             // 在庫なし商品の非表示オプションが有効な場合.
  491.             // if ($this->BaseInfo->isOptionNostockHidden()) {
  492.             //     if (!$Product->getStockFind()) {
  493.             //         return false;
  494.             //     }
  495.             // }
  496.             // 公開ステータスでない商品は表示しない.
  497.             if ($Product->getStatus()->getId() !== ProductStatus::DISPLAY_SHOW) {
  498.                 return false;
  499.             }
  500.         }
  501.         return true;
  502.     }
  503. }