src/Eccube/Controller/ProductController.php line 442

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.             'UUR' => [],
  159.             'UR' => [],
  160.             'SSP+' => [],
  161.             'SSP' => [],
  162.             'SSR' => [],
  163.             'HR' => [],
  164.             'SR' => [],
  165.             'SAR' => [],
  166.             'CSR' => [],
  167.             'AR' => [],
  168.             'CHR' => [],
  169.             'S' => [],
  170.             'A' => [],
  171.             'H' => [],
  172.             'K' => [],
  173.             'PR' => [],
  174.             'RRR' => [],
  175.             'RR' => [],
  176.             'R' => [],
  177.             'U' => [],
  178.             'C' => [],
  179.             'TR' => [],
  180.             'S-TD' => [],
  181.             'TD' => [],
  182.             'PROMO' => [],
  183.             '-' => [],
  184.         ];
  185.         $otherProducts = [];
  186.     
  187.         foreach ($allProducts as $Product) {
  188.             $isCategorized false;
  189.             foreach ($Product->getProductCategories() as $productCategory) {
  190.                 $category $productCategory->getCategory();
  191.                 switch ($category->getId()) {
  192.                      case 710:
  193.                         $groupedProducts['UUR'][] = $Product;
  194.                         $isCategorized true;
  195.                         break;
  196.                     case 621:
  197.                         $groupedProducts['UR'][] = $Product;
  198.                         $isCategorized true;
  199.                         break;
  200.                      case 708:
  201.                         $groupedProducts['SSP+'][] = $Product;
  202.                         $isCategorized true;
  203.                         break;
  204.                     case 709:
  205.                         $groupedProducts['SSP'][] = $Product;
  206.                         $isCategorized true;
  207.                         break;
  208.                     case 622:
  209.                     case 704:
  210.                         $groupedProducts['SSR'][] = $Product;
  211.                         $isCategorized true;
  212.                         break;
  213.                     case 623:
  214.                         $groupedProducts['HR'][] = $Product;
  215.                         $isCategorized true;
  216.                         break;
  217.                     case 624:
  218.                         $groupedProducts['SR'][] = $Product;
  219.                         $isCategorized true;
  220.                         break;
  221.                     case 625:
  222.                         $groupedProducts['SAR'][] = $Product;
  223.                         $isCategorized true;
  224.                         break;
  225.                     case 626:
  226.                         $groupedProducts['CSR'][] = $Product;
  227.                         $isCategorized true;
  228.                         break;
  229.                     case 627:
  230.                         $groupedProducts['AR'][] = $Product;
  231.                         $isCategorized true;
  232.                         break;
  233.                     case 628:
  234.                         $groupedProducts['CHR'][] = $Product;
  235.                         $isCategorized true;
  236.                         break;
  237.                     case 629:
  238.                         $groupedProducts['S'][] = $Product;
  239.                         $isCategorized true;
  240.                         break;
  241.                     case 630:
  242.                         $groupedProducts['A'][] = $Product;
  243.                         $isCategorized true;
  244.                         break;
  245.                     case 631:
  246.                         $groupedProducts['H'][] = $Product;
  247.                         $isCategorized true;
  248.                         break;
  249.                     case 632:
  250.                         $groupedProducts['K'][] = $Product;
  251.                         $isCategorized true;
  252.                         break;
  253.                     case 633:
  254.                         $groupedProducts['PR'][] = $Product;
  255.                         $isCategorized true;
  256.                         break;
  257.                     case 634:
  258.                         $groupedProducts['RRR'][] = $Product;
  259.                         $isCategorized true;
  260.                         break;
  261.                     case 635:
  262.                         $groupedProducts['RR'][] = $Product;
  263.                         $isCategorized true;
  264.                         break;
  265.                     case 636:
  266.                         $groupedProducts['R'][] = $Product;
  267.                         $isCategorized true;
  268.                         break;
  269.                     case 637:
  270.                         $groupedProducts['U'][] = $Product;
  271.                         $isCategorized true;
  272.                         break;
  273.                     case 638:
  274.                         $groupedProducts['C'][] = $Product;
  275.                         $isCategorized true;
  276.                         break;
  277.                     case 639:
  278.                         $groupedProducts['TR'][] = $Product;
  279.                         $isCategorized true;
  280.                         break;
  281.                     case 640:
  282.                         $groupedProducts['S-TD'][] = $Product;
  283.                         $isCategorized true;
  284.                         break;
  285.                     case 641:
  286.                         $groupedProducts['TD'][] = $Product;
  287.                         $isCategorized true;
  288.                         break;
  289.                     case 643:
  290.                         $groupedProducts['PROMO'][] = $Product;
  291.                         $isCategorized true;
  292.                         break;
  293.                     case 642:
  294.                         $groupedProducts['-'][] = $Product;
  295.                         $isCategorized true;
  296.                         break;
  297.                 }
  298.             }
  299.             // どのレアリティにも分類されなかった商品をotherProductsに追加
  300.             if (!$isCategorized) {
  301.                 $otherProducts[] = $Product;
  302.             }
  303.         }
  304.         // otherProductsをページング
  305.         /** @var SlidingPagination $otherProductsPagination */
  306.         $otherProductsPagination $paginator->paginate(
  307.             $otherProducts// ページングする配列
  308.             $request->query->getInt('pageno'1), // ページ番号
  309.             !empty($searchData['disp_number']) ? $searchData['disp_number']->getId() : $this->productListMaxRepository->findOneBy([], ['sort_no' => 'ASC'])->getId() // 1ページあたりの表示件数
  310.         );
  311.         
  312.         // ページネーション
  313.         /** @var SlidingPagination $pagination */
  314.         $pagination $paginator->paginate(
  315.             $qb,
  316.             $request->query->getInt('pageno'1),
  317.             !empty($searchData['disp_number']) ? $searchData['disp_number']->getId() : $this->productListMaxRepository->findOneBy([], ['sort_no' => 'ASC'])->getId()
  318.         );
  319.         $ids = [];
  320.         foreach ($pagination as $Product) {
  321.             $ids[] = $Product->getId();
  322.         }
  323.         $ProductsAndClassCategories $this->productRepository->findProductsWithSortedClassCategories($ids'p.id');
  324.         // addCart form
  325.         $forms = [];
  326.         foreach ($pagination as $Product) {
  327.             /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  328.             $builder $this->formFactory->createNamedBuilder(
  329.                 '',
  330.                 AddCartType::class,
  331.                 null,
  332.                 [
  333.                     'product' => $ProductsAndClassCategories[$Product->getId()],
  334.                     'allow_extra_fields' => true,
  335.                 ]
  336.             );
  337.             $addCartForm $builder->getForm();
  338.         
  339.             $forms[$Product->getId()] = $addCartForm->createView();
  340.         }
  341.     
  342.         $Category $searchForm->get('category_id')->getData();
  343.         $orderby $request->query->get('orderby'null); // フロントでの表示制御で使用
  344.         // カテゴリトップのみ、その他商品のページネーションを行う
  345.         if ($request->query->get('category_id') == || $request->query->get('category_id') == 8) {
  346.             $otherProducts $otherProductsPagination;
  347.         }
  348.         return [
  349.             'subtitle' => $this->getPageTitle($searchData),
  350.             'pagination' => $pagination,
  351.             'search_form' => $searchForm->createView(),
  352.             'forms' => $forms,
  353.             'Category' => $Category,
  354.             'groupedProducts' => $groupedProducts,
  355.             'otherProducts' => $otherProducts,
  356.             'orderby' => $orderby,
  357.         ];
  358.     }
  359.     /**
  360.      * 商品詳細画面.
  361.      *
  362.      * @Route("/products/detail/{id}", name="product_detail", methods={"GET"}, requirements={"id" = "\d+"})
  363.      * @Template("Product/detail.twig")
  364.      * @ParamConverter("Product", options={"repository_method" = "findWithSortedClassCategories"})
  365.      *
  366.      * @param Request $request
  367.      * @param Product $Product
  368.      *
  369.      * @return array
  370.      */
  371.     public function detail(Request $requestProduct $Product)
  372.     {
  373.         if (!$this->checkVisibility($Product)) {
  374.             throw new NotFoundHttpException();
  375.         }
  376.         $builder $this->formFactory->createNamedBuilder(
  377.             '',
  378.             AddCartType::class,
  379.             null,
  380.             [
  381.                 'product' => $Product,
  382.                 'id_add_product_id' => false,
  383.             ]
  384.         );
  385.         $event = new EventArgs(
  386.             [
  387.                 'builder' => $builder,
  388.                 'Product' => $Product,
  389.             ],
  390.             $request
  391.         );
  392.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE);
  393.         $is_favorite false;
  394.         if ($this->isGranted('ROLE_USER')) {
  395.             $Customer $this->getUser();
  396.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  397.         }
  398.         return [
  399.             'title' => $this->title,
  400.             'subtitle' => $Product->getName(),
  401.             'form' => $builder->getForm()->createView(),
  402.             'Product' => $Product,
  403.             'is_favorite' => $is_favorite,
  404.         ];
  405.     }
  406.     /**
  407.      * お気に入り追加.
  408.      *
  409.      * @Route("/products/add_favorite/{id}", name="product_add_favorite", requirements={"id" = "\d+"}, methods={"GET", "POST"})
  410.      */
  411.     public function addFavorite(Request $requestProduct $Product)
  412.     {
  413.         $this->checkVisibility($Product);
  414.         $event = new EventArgs(
  415.             [
  416.                 'Product' => $Product,
  417.             ],
  418.             $request
  419.         );
  420.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_INITIALIZE);
  421.         if ($this->isGranted('ROLE_USER')) {
  422.             $Customer $this->getUser();
  423.             $this->customerFavoriteProductRepository->addFavorite($Customer$Product);
  424.             $this->session->getFlashBag()->set('product_detail.just_added_favorite'$Product->getId());
  425.             $event = new EventArgs(
  426.                 [
  427.                     'Product' => $Product,
  428.                 ],
  429.                 $request
  430.             );
  431.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  432.             return $this->redirectToRoute('product_detail', ['id' => $Product->getId()]);
  433.         } else {
  434.             // 非会員の場合、ログイン画面を表示
  435.             //  ログイン後の画面遷移先を設定
  436.             $this->setLoginTargetPath($this->generateUrl('product_add_favorite', ['id' => $Product->getId()], UrlGeneratorInterface::ABSOLUTE_URL));
  437.             $this->session->getFlashBag()->set('eccube.add.favorite'true);
  438.             $event = new EventArgs(
  439.                 [
  440.                     'Product' => $Product,
  441.                 ],
  442.                 $request
  443.             );
  444.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  445.             return $this->redirectToRoute('mypage_login');
  446.         }
  447.     }
  448.     /**
  449.      * カートに追加.
  450.      *
  451.      * @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
  452.      */
  453.     public function addCart(Request $requestProduct $Product)
  454.     {
  455.         // エラーメッセージの配列
  456.         $errorMessages = [];
  457.         if (!$this->checkVisibility($Product)) {
  458.             throw new NotFoundHttpException();
  459.         }
  460.         $builder $this->formFactory->createNamedBuilder(
  461.             '',
  462.             AddCartType::class,
  463.             null,
  464.             [
  465.                 'product' => $Product,
  466.                 'id_add_product_id' => false,
  467.                 'allow_extra_fields' => true,
  468.             ]
  469.         );
  470.         $event = new EventArgs(
  471.             [
  472.                 'builder' => $builder,
  473.                 'Product' => $Product,
  474.             ],
  475.             $request
  476.         );
  477.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE);
  478.         /* @var $form \Symfony\Component\Form\FormInterface */
  479.         if(!empty($request->request->get('buyflg'))){
  480.             $form $builder->getForm(['allow_extra_fields' => true]);//'allow_extra_fields' => true
  481.         }else{
  482.             $form $builder->getForm();
  483.         }
  484.         $form->handleRequest($request);
  485.         if (!$form->isValid()) {
  486.             //理由:エラーが発生した場合はエラーメッセージを返す
  487.             foreach ($form->getErrors(true) as $error) {
  488.                 $errorMessages[] = $error;
  489.             }
  490.             dd($errorMessages);
  491.             throw new NotFoundHttpException();
  492.         }
  493.         $addCartData $form->getData();
  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.         if(!empty($request->request->get('buyflg'))){
  503.             $buyflg 1;
  504.         }else{
  505.             $buyflg 0;
  506.         }
  507.         //$buyflg = 1;//debug
  508.         
  509.         // カートへ追加
  510.         $this->cartService->addProduct($addCartData['product_class_id'], $addCartData['quantity'] , $buyflg);
  511.         // 明細の正規化
  512.         $Carts $this->cartService->getCarts(false $buyflg);
  513.         foreach ($Carts as $Cart) {
  514.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  515.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  516.             if ($result->hasError()) {
  517.                 $this->cartService->removeProduct($addCartData['product_class_id'] , $buyflg);
  518.                 foreach ($result->getErrors() as $error) {
  519.                     $errorMessages[] = $error->getMessage();
  520.                 }
  521.             }
  522.             foreach ($result->getWarning() as $warning) {
  523.                 $errorMessages[] = $warning->getMessage();
  524.             }
  525.         }
  526.         $this->cartService->save($buyflg);
  527.         log_info(
  528.             'カート追加処理完了',
  529.             [
  530.                 'product_id' => $Product->getId(),
  531.                 'product_class_id' => $addCartData['product_class_id'],
  532.                 'quantity' => $addCartData['quantity'],
  533.             ]
  534.         );
  535.         $event = new EventArgs(
  536.             [
  537.                 'form' => $form,
  538.                 'Product' => $Product,
  539.             ],
  540.             $request
  541.         );
  542.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE);
  543.         if ($event->getResponse() !== null) {
  544.             return $event->getResponse();
  545.         }
  546.         if ($request->isXmlHttpRequest()) {
  547.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  548.             // 初期化
  549.             $messages = [];
  550.             if (empty($errorMessages)) {
  551.                 // エラーが発生していない場合
  552.                 $done true;
  553.                 array_push($messagestrans('front.product.add_cart_complete'));
  554.             } else {
  555.                 // エラーが発生している場合
  556.                 $done false;
  557.                 $messages $errorMessages;
  558.             }
  559.             return $this->json(['done' => $done'messages' => $messages]);
  560.         } else {
  561.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  562.             foreach ($errorMessages as $errorMessage) {
  563.                 $this->addRequestError($errorMessage);
  564.             }
  565.             if($buyflg){
  566.                 return $this->redirectToRoute('buycart');
  567.             }else{
  568.                 return $this->redirectToRoute('cart');
  569.             }
  570.         }
  571.     }
  572.     /**
  573.      * ページタイトルの設定
  574.      *
  575.      * @param  array|null $searchData
  576.      *
  577.      * @return str
  578.      */
  579.     protected function getPageTitle($searchData)
  580.     {
  581.         if (isset($searchData['name']) && !empty($searchData['name'])) {
  582.             return trans('front.product.search_result');
  583.         } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
  584.             return $searchData['category_id']->getName();
  585.         } else {
  586.             return trans('front.product.all_products');
  587.         }
  588.     }
  589.     /**
  590.      * 閲覧可能な商品かどうかを判定
  591.      *
  592.      * @param Product $Product
  593.      *
  594.      * @return boolean 閲覧可能な場合はtrue
  595.      */
  596.     protected function checkVisibility(Product $Product)
  597.     {
  598.         $is_admin $this->session->has('_security_admin');
  599.         // 管理ユーザの場合はステータスやオプションにかかわらず閲覧可能.
  600.         if (!$is_admin) {
  601.             // 在庫なし商品の非表示オプションが有効な場合.
  602.             // if ($this->BaseInfo->isOptionNostockHidden()) {
  603.             //     if (!$Product->getStockFind()) {
  604.             //         return false;
  605.             //     }
  606.             // }
  607.             // 公開ステータスでない商品は表示しない.
  608.             if ($Product->getStatus()->getId() !== ProductStatus::DISPLAY_SHOW) {
  609.                 return false;
  610.             }
  611.         }
  612.         return true;
  613.     }
  614. }