src/Eccube/Controller/ProductController.php line 364

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 Eccube\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. use Eccube\Repository\CategoryRepository;
  37. class ProductController extends AbstractController
  38. {
  39.     /**
  40.      * @var PurchaseFlow
  41.      */
  42.     protected $purchaseFlow;
  43.     /**
  44.      * @var CustomerFavoriteProductRepository
  45.      */
  46.     protected $customerFavoriteProductRepository;
  47.     /**
  48.      * @var CartService
  49.      */
  50.     protected $cartService;
  51.     /**
  52.      * @var ProductRepository
  53.      */
  54.     protected $productRepository;
  55.     /**
  56.      * @var BaseInfo
  57.      */
  58.     protected $BaseInfo;
  59.     /**
  60.      * @var AuthenticationUtils
  61.      */
  62.     protected $helper;
  63.     /**
  64.      * @var ProductListMaxRepository
  65.      */
  66.     protected $productListMaxRepository;
  67.     private $title '';
  68.     /**
  69.      * ProductController constructor.
  70.      *
  71.      * @param PurchaseFlow $cartPurchaseFlow
  72.      * @param CustomerFavoriteProductRepository $customerFavoriteProductRepository
  73.      * @param CartService $cartService
  74.      * @param ProductRepository $productRepository
  75.      * @param BaseInfoRepository $baseInfoRepository
  76.      * @param AuthenticationUtils $helper
  77.      * @param ProductListMaxRepository $productListMaxRepository
  78.      */
  79.     public function __construct(
  80.         PurchaseFlow $cartPurchaseFlow,
  81.         CustomerFavoriteProductRepository $customerFavoriteProductRepository,
  82.         CartService $cartService,
  83.         ProductRepository $productRepository,
  84.         BaseInfoRepository $baseInfoRepository,
  85.         AuthenticationUtils $helper,
  86.         ProductListMaxRepository $productListMaxRepository
  87.     ) {
  88.         $this->purchaseFlow $cartPurchaseFlow;
  89.         $this->customerFavoriteProductRepository $customerFavoriteProductRepository;
  90.         $this->cartService $cartService;
  91.         $this->productRepository $productRepository;
  92.         $this->BaseInfo $baseInfoRepository->get();
  93.         $this->helper $helper;
  94.         $this->productListMaxRepository $productListMaxRepository;
  95.     }
  96.     /**
  97.      * 商品一覧画面.
  98.      *
  99.      * @Route("/products/list", name="product_list", methods={"GET"})
  100.      * @Template("Product/list.twig")
  101.      */
  102.     public function index(Request $requestPaginatorInterface $paginator)
  103.     {
  104.         // Doctrine SQLFilter
  105.         if ($this->BaseInfo->isOptionNostockHidden()) {
  106.             $this->entityManager->getFilters()->enable('option_nostock_hidden');
  107.         }
  108.     
  109.         // handleRequestは空のqueryの場合は無視するため
  110.         if ($request->getMethod() === 'GET') {
  111.             //$request->query->set('pageno', $request->query->get('pageno', ''));
  112.             $request->query->set('pageno'$request->query->get('pageno'1));
  113.         }
  114.     
  115.         // searchForm
  116.         /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  117.         $builder $this->formFactory->createNamedBuilder(''SearchProductType::class);
  118.     
  119.         if ($request->getMethod() === 'GET') {
  120.             $builder->setMethod('GET');
  121.         }
  122.     
  123.         $event = new EventArgs(
  124.             [
  125.                 'builder' => $builder,
  126.             ],
  127.             $request
  128.         );
  129.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_INITIALIZE);
  130.     
  131.         /* @var $searchForm \Symfony\Component\Form\FormInterface */
  132.         $searchForm $builder->getForm();
  133.         dump($searchForm->getData());
  134.         $searchForm->handleRequest($request);
  135.         
  136.         dump($searchForm->getData());
  137.         // paginatorの前に全商品の取得
  138.         $searchData $searchForm->getData();
  139.         $qb $this->productRepository->getQueryBuilderBySearchData($searchData);
  140.         dump($qb->getQuery()->getSQL());
  141.         //exit;
  142.         $event = new EventArgs(
  143.             [
  144.                 'searchData' => $searchData,
  145.                 'qb' => $qb,
  146.             ],
  147.             $request
  148.         );
  149.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_SEARCH);
  150.         $searchData $event->getArgument('searchData');
  151.         // 全商品のクエリを取得
  152.         $query $qb->getQuery()
  153.             ->useResultCache(true$this->eccubeConfig['eccube_result_cache_lifetime_short']);
  154.         
  155.         // 全ての商品を取得してグルーピング
  156.         $allProducts $query->getResult();
  157.         $groupedProducts = [
  158.             'UR' => [],
  159.             'SAR' => [],
  160.             'SSP' => [],
  161.             'SP' => [],
  162.             'RRR' => [],
  163.             'SR' => [],
  164.             'AR' => [],
  165.             'RR' => [],
  166.             'R' => [],
  167.             'UC' => [],
  168.             'C' => [],
  169.             'PR' => [],
  170.             'TD' => [],
  171.             'ホロ' => [],
  172.         ];
  173.         $otherProducts = [];
  174.     
  175.         foreach ($allProducts as $Product) {
  176.             $isCategorized false;
  177.             foreach ($Product->getProductCategories() as $productCategory) {
  178.                 $category $productCategory->getCategory();
  179.                 switch ($category->getId()) {
  180.                      case 621:
  181.                      //case 713:
  182.                         $groupedProducts['UR'][] = $Product;
  183.                         $isCategorized true;
  184.                         break;
  185.                     case 622:
  186.                     //case 714:
  187.                         $groupedProducts['SAR'][] = $Product;
  188.                         $isCategorized true;
  189.                         break;
  190.                     case 710:
  191.                     //case 732:
  192.                         $groupedProducts['SSP'][] = $Product;
  193.                         $isCategorized true;
  194.                         break;
  195.                     case 711:
  196.                     //case 733:
  197.                         $groupedProducts['SP'][] = $Product;
  198.                         $isCategorized true;
  199.                         break;
  200.                     case 712:
  201.                     //case 734:
  202.                         $groupedProducts['RRR'][] = $Product;
  203.                         $isCategorized true;
  204.                         break;
  205.                     case 623:
  206.                     //case 715:
  207.                     case 723:
  208.                     //case 735:
  209.                         $groupedProducts['SR'][] = $Product;
  210.                         $isCategorized true;
  211.                         break;
  212.                     case 624:
  213.                     case 716:
  214.                         $groupedProducts['AR'][] = $Product;
  215.                         $isCategorized true;
  216.                         break;
  217.                     case 625:
  218.                     //case 717:
  219.                     case 724:
  220.                     //case 736:
  221.                         $groupedProducts['RR'][] = $Product;
  222.                         $isCategorized true;
  223.                         break;
  224.                     case 626:
  225.                     //case 718:
  226.                     case 725:
  227.                     //case 737:
  228.                         $groupedProducts['R'][] = $Product;
  229.                         $isCategorized true;
  230.                         break;
  231.                     case 627:
  232.                     //case 719:
  233.                     case 726:
  234.                     //case 738:
  235.                         $groupedProducts['UC'][] = $Product;
  236.                         $isCategorized true;
  237.                         break;
  238.                     case 628:
  239.                     //case 720:
  240.                     case 727:
  241.                     //case 739:
  242.                         $groupedProducts['C'][] = $Product;
  243.                         $isCategorized true;
  244.                         break;
  245.                     case 728:
  246.                     //case 740:
  247.                         $groupedProducts['PR'][] = $Product;
  248.                         $isCategorized true;
  249.                         break;
  250.                     case 629:
  251.                     //case 721:
  252.                     case 729:
  253.                     //case 741:
  254.                         $groupedProducts['TD'][] = $Product;
  255.                         $isCategorized true;
  256.                         break;
  257.                     case 630:
  258.                     //case 722:
  259.                     case 730:
  260.                     //case 742:
  261.                         $groupedProducts['ホロ'][] = $Product;
  262.                         $isCategorized true;
  263.                         break;
  264.                 }
  265.             }
  266.             // どのレアリティにも分類されなかった商品をotherProductsに追加
  267.             if (!$isCategorized) {
  268.                 $otherProducts[] = $Product;
  269.             }
  270.         }
  271.         // otherProductsをページング
  272.         /** @var SlidingPagination $otherProductsPagination */
  273.         $otherProductsPagination $paginator->paginate(
  274.             $otherProducts// ページングする配列
  275.             $request->query->getInt('pageno'1), // ページ番号
  276.             !empty($searchData['disp_number']) ? $searchData['disp_number']->getId() : $this->productListMaxRepository->findOneBy([], ['sort_no' => 'ASC'])->getId() // 1ページあたりの表示件数
  277.         );
  278.         
  279.         // ページネーション
  280.         /** @var SlidingPagination $pagination */
  281.         $pagination $paginator->paginate(
  282.             $qb,
  283.             $request->query->getInt('pageno'1),
  284.             !empty($searchData['disp_number']) ? $searchData['disp_number']->getId() : $this->productListMaxRepository->findOneBy([], ['sort_no' => 'ASC'])->getId()
  285.         );
  286.         $ids = [];
  287.         foreach ($pagination as $Product) {
  288.             $ids[] = $Product->getId();
  289.         }
  290.         $ProductsAndClassCategories $this->productRepository->findProductsWithSortedClassCategories($ids'p.id');
  291.         // addCart form
  292.         $forms = [];
  293.         foreach ($pagination as $Product) {
  294.             /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  295.             $builder $this->formFactory->createNamedBuilder(
  296.                 '',
  297.                 AddCartType::class,
  298.                 null,
  299.                 [
  300.                     'product' => $ProductsAndClassCategories[$Product->getId()],
  301.                     'allow_extra_fields' => true,
  302.                 ]
  303.             );
  304.             $addCartForm $builder->getForm();
  305.         
  306.             $forms[$Product->getId()] = $addCartForm->createView();
  307.         }
  308.     
  309.         $Category $searchForm->get('category_id')->getData();
  310.         $orderby $request->query->get('orderby'null); // フロントでの表示制御で使用
  311.         // カテゴリトップのみ、その他商品のページネーションを行う
  312.         if ($request->query->get('category_id') == || $request->query->get('category_id') == 8) {
  313.             $otherProducts $otherProductsPagination;
  314.         }
  315.         return [
  316.             'subtitle' => $this->getPageTitle($searchData),
  317.             'pagination' => $pagination,
  318.             'search_form' => $searchForm->createView(),
  319.             'forms' => $forms,
  320.             'Category' => $Category,
  321.             'groupedProducts' => $groupedProducts,
  322.             'otherProducts' => $otherProducts,
  323.             'orderby' => $orderby,
  324.         ];
  325.     }
  326.     /**
  327.      * 商品詳細画面.
  328.      *
  329.      * @Route("/products/detail/{id}", name="product_detail", methods={"GET"}, requirements={"id" = "\d+"})
  330.      * @Template("Product/detail.twig")
  331.      * @ParamConverter("Product", options={"repository_method" = "findWithSortedClassCategories"})
  332.      *
  333.      * @param Request $request
  334.      * @param Product $Product
  335.      *
  336.      * @return array
  337.      */
  338.     public function detail(Request $requestProduct $Product)
  339.     {
  340.         if (!$this->checkVisibility($Product)) {
  341.             throw new NotFoundHttpException();
  342.         }
  343.         $builder $this->formFactory->createNamedBuilder(
  344.             '',
  345.             AddCartType::class,
  346.             null,
  347.             [
  348.                 'product' => $Product,
  349.                 'id_add_product_id' => false,
  350.             ]
  351.         );
  352.         $event = new EventArgs(
  353.             [
  354.                 'builder' => $builder,
  355.                 'Product' => $Product,
  356.             ],
  357.             $request
  358.         );
  359.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE);
  360.         $is_favorite false;
  361.         if ($this->isGranted('ROLE_USER')) {
  362.             $Customer $this->getUser();
  363.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  364.         }
  365.         return [
  366.             'title' => $this->title,
  367.             'subtitle' => $Product->getName(),
  368.             'form' => $builder->getForm()->createView(),
  369.             'Product' => $Product,
  370.             'is_favorite' => $is_favorite,
  371.         ];
  372.     }
  373.     /**
  374.      * お気に入り追加.
  375.      *
  376.      * @Route("/products/add_favorite/{id}", name="product_add_favorite", requirements={"id" = "\d+"}, methods={"GET", "POST"})
  377.      */
  378.     public function addFavorite(Request $requestProduct $Product)
  379.     {
  380.         $this->checkVisibility($Product);
  381.         $event = new EventArgs(
  382.             [
  383.                 'Product' => $Product,
  384.             ],
  385.             $request
  386.         );
  387.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_INITIALIZE);
  388.         if ($this->isGranted('ROLE_USER')) {
  389.             $Customer $this->getUser();
  390.             $this->customerFavoriteProductRepository->addFavorite($Customer$Product);
  391.             $this->session->getFlashBag()->set('product_detail.just_added_favorite'$Product->getId());
  392.             $event = new EventArgs(
  393.                 [
  394.                     'Product' => $Product,
  395.                 ],
  396.                 $request
  397.             );
  398.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  399.             return $this->redirectToRoute('product_detail', ['id' => $Product->getId()]);
  400.         } else {
  401.             // 非会員の場合、ログイン画面を表示
  402.             //  ログイン後の画面遷移先を設定
  403.             $this->setLoginTargetPath($this->generateUrl('product_add_favorite', ['id' => $Product->getId()], UrlGeneratorInterface::ABSOLUTE_URL));
  404.             $this->session->getFlashBag()->set('eccube.add.favorite'true);
  405.             $event = new EventArgs(
  406.                 [
  407.                     'Product' => $Product,
  408.                 ],
  409.                 $request
  410.             );
  411.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  412.             return $this->redirectToRoute('mypage_login');
  413.         }
  414.     }
  415.     /**
  416.      * カートに追加.
  417.      *
  418.      * @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
  419.      */
  420.     public function addCart(Request $requestProduct $Product)
  421.     {
  422.         // エラーメッセージの配列
  423.         $errorMessages = [];
  424.         if (!$this->checkVisibility($Product)) {
  425.             throw new NotFoundHttpException();
  426.         }
  427.         $builder $this->formFactory->createNamedBuilder(
  428.             '',
  429.             AddCartType::class,
  430.             null,
  431.             [
  432.                 'product' => $Product,
  433.                 'id_add_product_id' => false,
  434.                 'allow_extra_fields' => true,
  435.             ]
  436.         );
  437.         $event = new EventArgs(
  438.             [
  439.                 'builder' => $builder,
  440.                 'Product' => $Product,
  441.             ],
  442.             $request
  443.         );
  444.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE);
  445.         /* @var $form \Symfony\Component\Form\FormInterface */
  446.         if(!empty($request->request->get('buyflg'))){
  447.             $form $builder->getForm(['allow_extra_fields' => true]);//'allow_extra_fields' => true
  448.         }else{
  449.             $form $builder->getForm();
  450.         }
  451.         $form->handleRequest($request);
  452.         if (!$form->isValid()) {
  453.             //理由:エラーが発生した場合はエラーメッセージを返す
  454.             foreach ($form->getErrors(true) as $error) {
  455.                 $errorMessages[] = $error;
  456.             }
  457.             dd($errorMessages);
  458.             throw new NotFoundHttpException();
  459.         }
  460.         $addCartData $form->getData();
  461.         log_info(
  462.             'カート追加処理開始',
  463.             [
  464.                 'product_id' => $Product->getId(),
  465.                 'product_class_id' => $addCartData['product_class_id'],
  466.                 'quantity' => $addCartData['quantity'],
  467.             ]
  468.         );
  469.         if(!empty($request->request->get('buyflg'))){
  470.             $buyflg 1;
  471.         }else{
  472.             $buyflg 0;
  473.         }
  474.         //$buyflg = 1;//debug
  475.         
  476.         // カートへ追加
  477.         $this->cartService->addProduct($addCartData['product_class_id'], $addCartData['quantity'] , $buyflg);
  478.         // 明細の正規化
  479.         $Carts $this->cartService->getCarts(false $buyflg);
  480.         foreach ($Carts as $Cart) {
  481.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  482.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  483.             if ($result->hasError()) {
  484.                 $this->cartService->removeProduct($addCartData['product_class_id'] , $buyflg);
  485.                 foreach ($result->getErrors() as $error) {
  486.                     $errorMessages[] = $error->getMessage();
  487.                 }
  488.             }
  489.             foreach ($result->getWarning() as $warning) {
  490.                 $errorMessages[] = $warning->getMessage();
  491.             }
  492.         }
  493.         $this->cartService->save($buyflg);
  494.         log_info(
  495.             'カート追加処理完了',
  496.             [
  497.                 'product_id' => $Product->getId(),
  498.                 'product_class_id' => $addCartData['product_class_id'],
  499.                 'quantity' => $addCartData['quantity'],
  500.             ]
  501.         );
  502.         $event = new EventArgs(
  503.             [
  504.                 'form' => $form,
  505.                 'Product' => $Product,
  506.             ],
  507.             $request
  508.         );
  509.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE);
  510.         if ($event->getResponse() !== null) {
  511.             return $event->getResponse();
  512.         }
  513.         if ($request->isXmlHttpRequest()) {
  514.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  515.             // 初期化
  516.             $messages = [];
  517.             if (empty($errorMessages)) {
  518.                 // エラーが発生していない場合
  519.                 $done true;
  520.                 array_push($messagestrans('front.product.add_cart_complete'));
  521.             } else {
  522.                 // エラーが発生している場合
  523.                 $done false;
  524.                 $messages $errorMessages;
  525.             }
  526.             return $this->json(['done' => $done'messages' => $messages]);
  527.         } else {
  528.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  529.             foreach ($errorMessages as $errorMessage) {
  530.                 $this->addRequestError($errorMessage);
  531.             }
  532.             if($buyflg){
  533.                 return $this->redirectToRoute('buycart');
  534.             }else{
  535.                 return $this->redirectToRoute('cart');
  536.             }
  537.         }
  538.     }
  539.     /**
  540.      * ページタイトルの設定
  541.      *
  542.      * @param  array|null $searchData
  543.      *
  544.      * @return str
  545.      */
  546.     protected function getPageTitle($searchData)
  547.     {
  548.         if (isset($searchData['name']) && !empty($searchData['name'])) {
  549.             return trans('front.product.search_result');
  550.         } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
  551.             return $searchData['category_id']->getName();
  552.         } else {
  553.             return trans('front.product.all_products');
  554.         }
  555.     }
  556.     /**
  557.      * 閲覧可能な商品かどうかを判定
  558.      *
  559.      * @param Product $Product
  560.      *
  561.      * @return boolean 閲覧可能な場合はtrue
  562.      */
  563.     protected function checkVisibility(Product $Product)
  564.     {
  565.         $is_admin $this->session->has('_security_admin');
  566.         // 管理ユーザの場合はステータスやオプションにかかわらず閲覧可能.
  567.         if (!$is_admin) {
  568.             // 在庫なし商品の非表示オプションが有効な場合.
  569.             // if ($this->BaseInfo->isOptionNostockHidden()) {
  570.             //     if (!$Product->getStockFind()) {
  571.             //         return false;
  572.             //     }
  573.             // }
  574.             // 公開ステータスでない商品は表示しない.
  575.             if ($Product->getStatus()->getId() !== ProductStatus::DISPLAY_SHOW) {
  576.                 return false;
  577.             }
  578.         }
  579.         return true;
  580.     }
  581. }