app/Customize/Controller/ProductController.php line 568

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