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 Customize\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.         $mitsumori_json = @$_SESSION['mitsumori_json'];
  295.         if(empty($mitsumori_json)){ $mitsumori_json "{product_id:0, pw:'',pd:'',ph:'',pm:'',pc:'',op:['','','','','','','','','','','']}"; }
  296.         $mitsumori_json_obj json_decode($mitsumori_json);
  297.         if(empty($mitsumori_json_obj) || $mitsumori_json_obj->product_id != $Product->getId()){
  298.             $mitsumori_json_obj json_decode("{product_id:0, pw:'',pd:'',ph:'',pm:'',pc:'',op:['','','','','','','','','','','']}");
  299.         }
  300.         return [
  301.             'title' => $this->title,
  302.             'subtitle' => $Product->getName(),
  303.             'form' => $builder->getForm()->createView(),
  304.             'Product' => $Product,
  305.             'color' => $color,
  306.             'pp' => json_encode($pp),
  307.             'base_select1' => @$base_select1["b_meta_content"],
  308.             'base_select2' => @$base_select2["b_meta_content"],
  309.             'base_select3' => @$base_select3["b_meta_content"],
  310.             'related_product1' => $related_product1,
  311.             'related_product2' => $related_product2,
  312.             'related_product3' => $related_product3,
  313.             'mitsumori_json' => $mitsumori_json_obj,
  314.             'p_w' => $p_w,
  315.             'p_d' => $p_d,
  316.             'p_h' => $p_h,
  317.             'p_m' => $p_m,
  318.             'p_c' => $p_c,
  319.             'op' => $op,
  320.             'oi' => $oi,
  321.             'ProductClass' => $ProductClass,
  322.             'is_favorite' => $is_favorite,
  323.         ];
  324.     }
  325.     /**
  326.      * お気に入り追加.
  327.      *
  328.      * @Route("/products/add_favorite/{id}", name="product_add_favorite", requirements={"id" = "\d+"}, methods={"GET", "POST"})
  329.      */
  330.     public function addFavorite(Request $requestProduct $Product)
  331.     {
  332.         $this->checkVisibility($Product);
  333.         $event = new EventArgs(
  334.             [
  335.                 'Product' => $Product,
  336.             ],
  337.             $request
  338.         );
  339.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_INITIALIZE);
  340.         if ($this->isGranted('ROLE_USER')) {
  341.             $Customer $this->getUser();
  342.             $this->customerFavoriteProductRepository->addFavorite($Customer$Product);
  343.             $this->session->getFlashBag()->set('product_detail.just_added_favorite'$Product->getId());
  344.             $event = new EventArgs(
  345.                 [
  346.                     'Product' => $Product,
  347.                 ],
  348.                 $request
  349.             );
  350.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  351.             return $this->redirectToRoute('product_detail', ['id' => $Product->getId()]);
  352.         } else {
  353.             // 非会員の場合、ログイン画面を表示
  354.             //  ログイン後の画面遷移先を設定
  355.             $this->setLoginTargetPath($this->generateUrl('product_add_favorite', ['id' => $Product->getId()], UrlGeneratorInterface::ABSOLUTE_URL));
  356.             $this->session->getFlashBag()->set('eccube.add.favorite'true);
  357.             $event = new EventArgs(
  358.                 [
  359.                     'Product' => $Product,
  360.                 ],
  361.                 $request
  362.             );
  363.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  364.             return $this->redirectToRoute('mypage_login');
  365.         }
  366.     }
  367.     /**
  368.      * カートに追加.
  369.      *
  370.      * @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
  371.      */
  372.     public function addCart(Request $requestProduct $Product)
  373.     {
  374.         if(!empty($_POST['mitsumori_json'])){
  375.             $_SESSION['mitsumori_json'] = $_POST['mitsumori_json'];
  376.         }
  377.         // エラーメッセージの配列
  378.         $errorMessages = [];
  379.         if (!$this->checkVisibility($Product)) {
  380.             throw new NotFoundHttpException();
  381.         }
  382.         $builder $this->formFactory->createNamedBuilder(
  383.             '',
  384.             AddCartType::class,
  385.             null,
  386.             [
  387.                 'product' => $Product,
  388.                 'id_add_product_id' => false,
  389.             ]
  390.         );
  391.         $event = new EventArgs(
  392.             [
  393.                 'builder' => $builder,
  394.                 'Product' => $Product,
  395.             ],
  396.             $request
  397.         );
  398.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE);
  399.         /* @var $form \Symfony\Component\Form\FormInterface */
  400.         $form $builder->getForm();
  401.         $form->handleRequest($request);
  402.         if (!$form->isValid()) {
  403.             throw new NotFoundHttpException();
  404.         }
  405.         $addCartData $form->getData();
  406.         log_info(
  407.             'カート追加処理開始',
  408.             [
  409.                 'product_id' => $Product->getId(),
  410.                 'product_class_id' => $addCartData['product_class_id'],
  411.                 'quantity' => $addCartData['quantity'],
  412.             ]
  413.         );
  414.         // カートへ追加
  415.         $this->cartService->addProduct($addCartData['product_class_id'], $addCartData['quantity']);
  416.         // 明細の正規化
  417.         $Carts $this->cartService->getCarts();
  418.         foreach ($Carts as $Cart) {
  419.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  420.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  421.             if ($result->hasError()) {
  422.                 $this->cartService->removeProduct($addCartData['product_class_id']);
  423.                 foreach ($result->getErrors() as $error) {
  424.                     $errorMessages[] = $error->getMessage();
  425.                 }
  426.             }
  427.             foreach ($result->getWarning() as $warning) {
  428.                 $errorMessages[] = $warning->getMessage();
  429.             }
  430.         }
  431.         $this->cartService->save();
  432.         log_info(
  433.             'カート追加処理完了',
  434.             [
  435.                 'product_id' => $Product->getId(),
  436.                 'product_class_id' => $addCartData['product_class_id'],
  437.                 'quantity' => $addCartData['quantity'],
  438.             ]
  439.         );
  440.         $event = new EventArgs(
  441.             [
  442.                 'form' => $form,
  443.                 'Product' => $Product,
  444.             ],
  445.             $request
  446.         );
  447.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE);
  448.         if ($event->getResponse() !== null) {
  449.             return $event->getResponse();
  450.         }
  451.         if ($request->isXmlHttpRequest()) {
  452.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  453.             // 初期化
  454.             $messages = [];
  455.             if (empty($errorMessages)) {
  456.                 // エラーが発生していない場合
  457.                 $done true;
  458.                 array_push($messagestrans('front.product.add_cart_complete'));
  459.             } else {
  460.                 // エラーが発生している場合
  461.                 $done false;
  462.                 $messages $errorMessages;
  463.             }
  464.             return $this->json(['done' => $done'messages' => $messages]);
  465.         } else {
  466.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  467.             foreach ($errorMessages as $errorMessage) {
  468.                 $this->addRequestError($errorMessage);
  469.             }
  470.             return $this->redirectToRoute('cart');
  471.         }
  472.     }
  473.     /**
  474.      * ページタイトルの設定
  475.      *
  476.      * @param  array|null $searchData
  477.      *
  478.      * @return str
  479.      */
  480.     protected function getPageTitle($searchData)
  481.     {
  482.         if (isset($searchData['name']) && !empty($searchData['name'])) {
  483.             return trans('front.product.search_result');
  484.         } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
  485.             return $searchData['category_id']->getName();
  486.         } else {
  487.             return trans('front.product.all_products');
  488.         }
  489.     }
  490.     /**
  491.      * 閲覧可能な商品かどうかを判定
  492.      *
  493.      * @param Product $Product
  494.      *
  495.      * @return boolean 閲覧可能な場合はtrue
  496.      */
  497.     protected function checkVisibility(Product $Product)
  498.     {
  499.         $is_admin $this->session->has('_security_admin');
  500.         // 管理ユーザの場合はステータスやオプションにかかわらず閲覧可能.
  501.         if (!$is_admin) {
  502.             // 在庫なし商品の非表示オプションが有効な場合.
  503.             // if ($this->BaseInfo->isOptionNostockHidden()) {
  504.             //     if (!$Product->getStockFind()) {
  505.             //         return false;
  506.             //     }
  507.             // }
  508.             // 公開ステータスでない商品は表示しない.
  509.             if ($Product->getStatus()->getId() !== ProductStatus::DISPLAY_SHOW) {
  510.                 return false;
  511.             }
  512.         }
  513.         return true;
  514.     }
  515. }