app/Customize/Controller/ProductController.php line 551

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.         $event = new EventArgs(
  210.             [
  211.                 'builder' => $builder,
  212.                 'Product' => $Product,
  213.             ],
  214.             $request
  215.         );
  216.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE);
  217.         $is_favorite false;
  218.         if ($this->isGranted('ROLE_USER')) {
  219.             $Customer $this->getUser();
  220.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  221.         }
  222.         $color = array();
  223.         if(!empty($Product->getSearchWord())){
  224.             $color unserialize($Product->getSearchWord());
  225.         }
  226.         $pp = array();
  227.         $p_w = array();
  228.         $p_d = array();
  229.         $p_h = array();
  230.         $p_m = array();
  231.         $p_c = array();
  232.         if(!empty($Product->getFreeArea())){
  233.             $pp_price unserialize($Product->getFreeArea());
  234.             foreach($pp_price as $key => $item){
  235.                 if(empty($item['ct'])){ $item['ct'] = 0; }
  236.                 $pp[] = $item;
  237.                 $p_w[$item['w']] = $item['w'];
  238.                 $p_c[$item['c']] = $item['c'];
  239.                 $p_d[$item['d']] = $item['d'];
  240.                 $p_h[$item['h']] = $item['h'];
  241.                 $p_m[$item['m']] = $item['m'];
  242.             }
  243.         }
  244.         $op = array();
  245.         if(!empty($Product->getOptionArea())){
  246.             $op unserialize($Product->getOptionArea());
  247.         }
  248.         $oi = array();
  249.         if(!empty($Product->getOptionItemArea())){
  250.             $oi_tmp unserialize($Product->getOptionItemArea());
  251.             foreach($oi_tmp as $key => $item){
  252.                 $oi[] = $item;
  253.             }
  254.         }
  255.         $ProductClasses $Product->getProductClasses();
  256.         $ProductClass $ProductClasses[0];
  257.         $Configs $this->ConfigRepository->joinMetaKeyFind($Product->getId(),'related_product');
  258.         $meta_array unserialize($Configs["b_meta_content"]);
  259.         $related_product $this->productRepository->findBy(["id" => $meta_array,'Status' => 1]);
  260.         $base_select1 $this->ConfigRepository->joinMetaKeyFind($Product->getId(),'related_selected1');
  261.         $base_select2 $this->ConfigRepository->joinMetaKeyFind($Product->getId(),'related_selected2');
  262.         $base_select3 $this->ConfigRepository->joinMetaKeyFind($Product->getId(),'related_selected3');
  263.         $related_product1 = array();
  264.         $related_product2 = array();
  265.         $related_product3 = array();
  266.         $registed_select1 = array();
  267.         $registed_select2 = array();
  268.         $registed_select3 = array();
  269.         foreach($related_product as $rp){
  270.             $select_name1 $this->ConfigRepository->joinMetaKeyFind($rp->getId(),'related_selected1');
  271.             $select_name2 $this->ConfigRepository->joinMetaKeyFind($rp->getId(),'related_selected2');
  272.             $select_name3 $this->ConfigRepository->joinMetaKeyFind($rp->getId(),'related_selected3');
  273.             if(!in_array($select_name1["b_meta_content"],$registed_select1)){
  274.                 $registed_select1[$select_name1["b_meta_content"]] = $select_name1["b_meta_content"];
  275.                 $related_product1[$rp->getId()] = $select_name1["b_meta_content"];
  276.             }
  277.             if(!in_array($select_name2["b_meta_content"],$registed_select2) && $base_select1["b_meta_content"] == $select_name1["b_meta_content"]){
  278.                 $registed_select2[$select_name2["b_meta_content"]] = $select_name2["b_meta_content"];
  279.                 $related_product2[$rp->getId()] = $select_name2["b_meta_content"];
  280.             }
  281.             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"]){
  282.                 $registed_select3[$select_name3["b_meta_content"]] = $select_name3["b_meta_content"];
  283.                 $related_product3[$rp->getId()] = $select_name3["b_meta_content"];
  284.             }
  285.         }
  286.         asort($related_product1);
  287.         asort($related_product2);
  288.         asort($related_product3);
  289.         
  290.         return [
  291.             'title' => $this->title,
  292.             'subtitle' => $Product->getName(),
  293.             'form' => $builder->getForm()->createView(),
  294.             'Product' => $Product,
  295.             'color' => $color,
  296.             'pp' => json_encode($pp),
  297.             'base_select1' => @$base_select1["b_meta_content"],
  298.             'base_select2' => @$base_select2["b_meta_content"],
  299.             'base_select3' => @$base_select3["b_meta_content"],
  300.             'related_product1' => $related_product1,
  301.             'related_product2' => $related_product2,
  302.             'related_product3' => $related_product3,
  303.             'p_w' => $p_w,
  304.             'p_d' => $p_d,
  305.             'p_h' => $p_h,
  306.             'p_m' => $p_m,
  307.             'p_c' => $p_c,
  308.             'op' => $op,
  309.             'oi' => $oi,
  310.             'ProductClass' => $ProductClass,
  311.             'is_favorite' => $is_favorite,
  312.         ];
  313.     }
  314.     /**
  315.      * お気に入り追加.
  316.      *
  317.      * @Route("/products/add_favorite/{id}", name="product_add_favorite", requirements={"id" = "\d+"}, methods={"GET", "POST"})
  318.      */
  319.     public function addFavorite(Request $requestProduct $Product)
  320.     {
  321.         $this->checkVisibility($Product);
  322.         $event = new EventArgs(
  323.             [
  324.                 'Product' => $Product,
  325.             ],
  326.             $request
  327.         );
  328.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_INITIALIZE);
  329.         if ($this->isGranted('ROLE_USER')) {
  330.             $Customer $this->getUser();
  331.             $this->customerFavoriteProductRepository->addFavorite($Customer$Product);
  332.             $this->session->getFlashBag()->set('product_detail.just_added_favorite'$Product->getId());
  333.             $event = new EventArgs(
  334.                 [
  335.                     'Product' => $Product,
  336.                 ],
  337.                 $request
  338.             );
  339.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  340.             return $this->redirectToRoute('product_detail', ['id' => $Product->getId()]);
  341.         } else {
  342.             // 非会員の場合、ログイン画面を表示
  343.             //  ログイン後の画面遷移先を設定
  344.             $this->setLoginTargetPath($this->generateUrl('product_add_favorite', ['id' => $Product->getId()], UrlGeneratorInterface::ABSOLUTE_URL));
  345.             $this->session->getFlashBag()->set('eccube.add.favorite'true);
  346.             $event = new EventArgs(
  347.                 [
  348.                     'Product' => $Product,
  349.                 ],
  350.                 $request
  351.             );
  352.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  353.             return $this->redirectToRoute('mypage_login');
  354.         }
  355.     }
  356.     /**
  357.      * カートに追加.
  358.      *
  359.      * @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
  360.      */
  361.     public function addCart(Request $requestProduct $Product)
  362.     {
  363.         // エラーメッセージの配列
  364.         $errorMessages = [];
  365.         if (!$this->checkVisibility($Product)) {
  366.             throw new NotFoundHttpException();
  367.         }
  368.         $builder $this->formFactory->createNamedBuilder(
  369.             '',
  370.             AddCartType::class,
  371.             null,
  372.             [
  373.                 'product' => $Product,
  374.                 'id_add_product_id' => false,
  375.             ]
  376.         );
  377.         $event = new EventArgs(
  378.             [
  379.                 'builder' => $builder,
  380.                 'Product' => $Product,
  381.             ],
  382.             $request
  383.         );
  384.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE);
  385.         /* @var $form \Symfony\Component\Form\FormInterface */
  386.         $form $builder->getForm();
  387.         $form->handleRequest($request);
  388.         if (!$form->isValid()) {
  389.             throw new NotFoundHttpException();
  390.         }
  391.         $addCartData $form->getData();
  392.         log_info(
  393.             'カート追加処理開始',
  394.             [
  395.                 'product_id' => $Product->getId(),
  396.                 'product_class_id' => $addCartData['product_class_id'],
  397.                 'quantity' => $addCartData['quantity'],
  398.             ]
  399.         );
  400.         // カートへ追加
  401.         $this->cartService->addProduct($addCartData['product_class_id'], $addCartData['quantity']);
  402.         // 明細の正規化
  403.         $Carts $this->cartService->getCarts();
  404.         foreach ($Carts as $Cart) {
  405.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  406.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  407.             if ($result->hasError()) {
  408.                 $this->cartService->removeProduct($addCartData['product_class_id']);
  409.                 foreach ($result->getErrors() as $error) {
  410.                     $errorMessages[] = $error->getMessage();
  411.                 }
  412.             }
  413.             foreach ($result->getWarning() as $warning) {
  414.                 $errorMessages[] = $warning->getMessage();
  415.             }
  416.         }
  417.         $this->cartService->save();
  418.         log_info(
  419.             'カート追加処理完了',
  420.             [
  421.                 'product_id' => $Product->getId(),
  422.                 'product_class_id' => $addCartData['product_class_id'],
  423.                 'quantity' => $addCartData['quantity'],
  424.             ]
  425.         );
  426.         $event = new EventArgs(
  427.             [
  428.                 'form' => $form,
  429.                 'Product' => $Product,
  430.             ],
  431.             $request
  432.         );
  433.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE);
  434.         if ($event->getResponse() !== null) {
  435.             return $event->getResponse();
  436.         }
  437.         if ($request->isXmlHttpRequest()) {
  438.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  439.             // 初期化
  440.             $messages = [];
  441.             if (empty($errorMessages)) {
  442.                 // エラーが発生していない場合
  443.                 $done true;
  444.                 array_push($messagestrans('front.product.add_cart_complete'));
  445.             } else {
  446.                 // エラーが発生している場合
  447.                 $done false;
  448.                 $messages $errorMessages;
  449.             }
  450.             return $this->json(['done' => $done'messages' => $messages]);
  451.         } else {
  452.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  453.             foreach ($errorMessages as $errorMessage) {
  454.                 $this->addRequestError($errorMessage);
  455.             }
  456.             return $this->redirectToRoute('cart');
  457.         }
  458.     }
  459.     /**
  460.      * ページタイトルの設定
  461.      *
  462.      * @param  array|null $searchData
  463.      *
  464.      * @return str
  465.      */
  466.     protected function getPageTitle($searchData)
  467.     {
  468.         if (isset($searchData['name']) && !empty($searchData['name'])) {
  469.             return trans('front.product.search_result');
  470.         } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
  471.             return $searchData['category_id']->getName();
  472.         } else {
  473.             return trans('front.product.all_products');
  474.         }
  475.     }
  476.     /**
  477.      * 閲覧可能な商品かどうかを判定
  478.      *
  479.      * @param Product $Product
  480.      *
  481.      * @return boolean 閲覧可能な場合はtrue
  482.      */
  483.     protected function checkVisibility(Product $Product)
  484.     {
  485.         $is_admin $this->session->has('_security_admin');
  486.         // 管理ユーザの場合はステータスやオプションにかかわらず閲覧可能.
  487.         if (!$is_admin) {
  488.             // 在庫なし商品の非表示オプションが有効な場合.
  489.             // if ($this->BaseInfo->isOptionNostockHidden()) {
  490.             //     if (!$Product->getStockFind()) {
  491.             //         return false;
  492.             //     }
  493.             // }
  494.             // 公開ステータスでない商品は表示しない.
  495.             if ($Product->getStatus()->getId() !== ProductStatus::DISPLAY_SHOW) {
  496.                 return false;
  497.             }
  498.         }
  499.         return true;
  500.     }
  501. }