app/Customize/Controller/ProductController.php line 557

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