src/Eccube/Controller/ProductController.php line 312

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\SearchProductBlockType;
  20. use Eccube\Form\Type\SearchProductType;
  21. use Eccube\Repository\BaseInfoRepository;
  22. use Eccube\Repository\CustomerFavoriteProductRepository;
  23. use Eccube\Repository\Master\ProductListMaxRepository;
  24. use Eccube\Repository\ProductRepository;
  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 Plugin\SearchPlus42\Service\SearchPlusService;
  31. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  32. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  33. use Symfony\Component\HttpFoundation\Request;
  34. use Symfony\Component\HttpFoundation\RequestStack;
  35. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  36. use Symfony\Component\Routing\Annotation\Route;
  37. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  38. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  39. class ProductController extends AbstractController
  40. {
  41.     /**
  42.      * @var PurchaseFlow
  43.      */
  44.     protected $purchaseFlow;
  45.     /**
  46.      * @var CustomerFavoriteProductRepository
  47.      */
  48.     protected $customerFavoriteProductRepository;
  49.     /**
  50.      * @var CartService
  51.      */
  52.     protected $cartService;
  53.     /**
  54.      * @var ProductRepository
  55.      */
  56.     protected $productRepository;
  57.     /**
  58.      * @var BaseInfo
  59.      */
  60.     protected $BaseInfo;
  61.     /**
  62.      * @var AuthenticationUtils
  63.      */
  64.     protected $helper;
  65.     /**
  66.      * @var ProductListMaxRepository
  67.      */
  68.     protected $productListMaxRepository;
  69.     private $title '';
  70.     protected $requestStack;
  71.     private $searchPlusService;
  72.     /**
  73.      * ProductController constructor.
  74.      *
  75.      * @param PurchaseFlow $cartPurchaseFlow
  76.      * @param CustomerFavoriteProductRepository $customerFavoriteProductRepository
  77.      * @param CartService $cartService
  78.      * @param ProductRepository $productRepository
  79.      * @param BaseInfoRepository $baseInfoRepository
  80.      * @param AuthenticationUtils $helper
  81.      * @param ProductListMaxRepository $productListMaxRepository
  82.      */
  83.     public function __construct(
  84.         PurchaseFlow $cartPurchaseFlow,
  85.         CustomerFavoriteProductRepository $customerFavoriteProductRepository,
  86.         CartService $cartService,
  87.         ProductRepository $productRepository,
  88.         BaseInfoRepository $baseInfoRepository,
  89.         AuthenticationUtils $helper,
  90.         ProductListMaxRepository $productListMaxRepository,
  91.         RequestStack $requestStack,
  92.         SearchPlusService $searchPlusService
  93.     ) {
  94.         $this->purchaseFlow $cartPurchaseFlow;
  95.         $this->customerFavoriteProductRepository $customerFavoriteProductRepository;
  96.         $this->cartService $cartService;
  97.         $this->productRepository $productRepository;
  98.         $this->BaseInfo $baseInfoRepository->get();
  99.         $this->helper $helper;
  100.         $this->productListMaxRepository $productListMaxRepository;
  101.         $this->requestStack $requestStack;
  102.         $this->searchPlusService $searchPlusService;
  103.     }
  104.     /**
  105.      * 商品一覧画面.
  106.      *
  107.      * @Route("/products/list", name="product_list", methods={"GET"})
  108.      */
  109.     public function index(Request $requestPaginatorInterface $paginator)
  110.     {
  111.         // Doctrine SQLFilter
  112.         if ($this->BaseInfo->isOptionNostockHidden()) {
  113.             $this->entityManager->getFilters()->enable('option_nostock_hidden');
  114.         }
  115.         // handleRequestは空のqueryの場合は無視するため
  116.         if ($request->getMethod() === 'GET') {
  117.             $request->query->set('pageno'$request->query->get('pageno'''));
  118.         }
  119.         // searchForm
  120.         /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  121.         $builder $this->formFactory->createNamedBuilder(''SearchProductType::class);
  122.         if ($request->getMethod() === 'GET') {
  123.             $builder->setMethod('GET');
  124.         }
  125.         $event = new EventArgs(
  126.             [
  127.                 'builder' => $builder,
  128.             ],
  129.             $request
  130.         );
  131.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_INITIALIZE);
  132.         /* @var $searchForm \Symfony\Component\Form\FormInterface */
  133.         $searchForm $builder->getForm();
  134.         $searchForm->handleRequest($request);
  135.         // paginator
  136.         $searchData $searchForm->getData();
  137.         $qb $this->productRepository->getQueryBuilderBySearchData($searchData);
  138.         $event = new EventArgs(
  139.             [
  140.                 'searchData' => $searchData,
  141.                 'qb' => $qb,
  142.             ],
  143.             $request
  144.         );
  145.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_SEARCH);
  146.         $searchData $event->getArgument('searchData');
  147.         $query $qb->getQuery()
  148.             ->useResultCache(true$this->eccubeConfig['eccube_result_cache_lifetime_short']);
  149.         /** @var SlidingPagination $pagination */
  150.         $pagination $paginator->paginate(
  151.             $query,
  152.             !empty($searchData['pageno']) ? $searchData['pageno'] : 1,
  153.             !empty($searchData['disp_number']) ? $searchData['disp_number']->getId() : $this->productListMaxRepository->findOneBy([], ['sort_no' => 'ASC'])->getId()
  154.         );
  155.         $ids = [];
  156.         foreach ($pagination as $Product) {
  157.             $ids[] = $Product->getId();
  158.         }
  159.         $ProductsAndClassCategories $this->productRepository->findProductsWithSortedClassCategories($ids'p.id');
  160.         // addCart form
  161.         $forms = [];
  162.         foreach ($pagination as $Product) {
  163.             /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  164.             $builder $this->formFactory->createNamedBuilder(
  165.                 '',
  166.                 AddCartType::class,
  167.                 null,
  168.                 [
  169.                     'product' => $ProductsAndClassCategories[$Product->getId()],
  170.                     'allow_extra_fields' => true,
  171.                 ]
  172.             );
  173.             $addCartForm $builder->getForm();
  174.             $forms[$Product->getId()] = $addCartForm->createView();
  175.         }
  176.         $Category $searchForm->get('category_id')->getData();
  177.         $template 'Product/list.twig'// デフォルトのテンプレート
  178.         //商品カテゴリとブランドの判定
  179.         $category_result false;
  180.         $brand_result false;
  181.         if ($Category) {
  182.             $Parent $Category->getParent();
  183.             if ($Parent) {
  184.                 if ($Parent->getId() == 7) {
  185.                     $template 'Product/list_category.twig';
  186.                     $category_result true;
  187.                 } elseif ($Parent->getId() == 34) {
  188.                     $template 'Product/list_brand.twig';
  189.                     $brand_result true;
  190.                 }
  191.             }
  192.         }
  193.         //検索項目
  194.         $searchData = [
  195.             'hmin' => $request->query->get('hmin'),
  196.             'hmax' => $request->query->get('hmax'),
  197.             'wmin' => $request->query->get('wmin'),
  198.             'wmax' => $request->query->get('wmax'),
  199.         ];
  200.         $ProductItems = [];
  201.         if($this->searchPlusService->checkInstallPlugin('ProductPlus42')){
  202.             $productItemRepository $this->entityManager->getRepository('Plugin\ProductPlus42\Entity\ProductItem');
  203.             $request $this->requestStack->getMasterRequest();
  204.             $category_id $request->query->get('category_id');
  205.             $criteria = ['search_flg' => true];
  206.             //カテゴリごとの検索項目出力を連想配列に格納
  207.             $categoryItemsMap = [
  208.                 10 => [1567],//ソファ
  209.                 11 => [8],//チェア
  210.                 12 => [],//スツール
  211.                 13 => [],//ベンチ
  212.                 15 => [967],//テーブル
  213.                 16 => [1067],//サイドテーブル
  214.                 17 => [1167],//ダイニング
  215.                 18 => [121367],//デスク
  216.                 19 => [1415],//テレビボード
  217.                 20 => [1667],//収納家具
  218.                 21 => [17],//キッチン収納・食器棚
  219.                 22 => [18],//ベッド
  220.                 23 => [28],//マットレス
  221.                 24 => [19],//寝具
  222.                 25 => [202122],//ラグ
  223.                 26 => [23],//キッズ
  224.                 27 => [67],//カーテン
  225.                 28 => [24],//オフィス
  226.                 29 => [25],//アウトドア
  227.                 30 => [67],//ガーデンファニチャー
  228.                 31 => [26],//クッション
  229.                 32 => [27],//時計
  230.                 33 => [67],//インテリア雑貨
  231.             ];
  232.             if (array_key_exists($category_id$categoryItemsMap)) {
  233.                 $criteria['id'] = $categoryItemsMap[$category_id];
  234.             } else {
  235.                 $criteria['id'] = [];
  236.             }
  237.             $ProductItems $productItemRepository->findBy($criteria, ['sort_no' => 'DESC']);
  238.         }
  239.         //検索フォーム
  240.         $builder $this->formFactory
  241.             ->createNamedBuilder(''SearchProductBlockType::class)
  242.             ->setMethod('GET');
  243.         $form $builder->getForm();
  244.         $form->handleRequest($request);
  245.         return $this->render($template, [
  246.             'ProductItems' => $ProductItems,
  247.             'subtitle' => $this->getPageTitle($searchData),
  248.             'pagination' => $pagination,
  249.             'search_form' => $searchForm->createView(),
  250.             'forms' => $forms,
  251.             'Category' => $Category,
  252.             'CategoryResult' => $category_result,
  253.             'BrandResult' => $brand_result,
  254.             'searchData' => $searchData,
  255.             'form' => $form->createView(),
  256.         ]);
  257.     }
  258.     /**
  259.      * 商品詳細画面.
  260.      *
  261.      * @Route("/products/detail/{id}", name="product_detail", methods={"GET"}, requirements={"id" = "\d+"})
  262.      * @Template("Product/detail.twig")
  263.      * @ParamConverter("Product", options={"repository_method" = "findWithSortedClassCategories"})
  264.      *
  265.      * @param Request $request
  266.      * @param Product $Product
  267.      *
  268.      * @return array
  269.      */
  270.     public function detail(Request $requestProduct $Product)
  271.     {
  272.         if (!$this->checkVisibility($Product)) {
  273.             throw new NotFoundHttpException();
  274.         }
  275.         $builder $this->formFactory->createNamedBuilder(
  276.             '',
  277.             AddCartType::class,
  278.             null,
  279.             [
  280.                 'product' => $Product,
  281.                 'id_add_product_id' => false,
  282.             ]
  283.         );
  284.         $event = new EventArgs(
  285.             [
  286.                 'builder' => $builder,
  287.                 'Product' => $Product,
  288.             ],
  289.             $request
  290.         );
  291.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE);
  292.         $is_favorite false;
  293.         if ($this->isGranted('ROLE_USER')) {
  294.             $Customer $this->getUser();
  295.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  296.         }
  297.         return [
  298.             'title' => $this->title,
  299.             'subtitle' => $Product->getName(),
  300.             'form' => $builder->getForm()->createView(),
  301.             'Product' => $Product,
  302.             'is_favorite' => $is_favorite,
  303.         ];
  304.     }
  305.     /**
  306.      * @Route("/products/detail_app/{id}", name="product_detail_app", methods={"GET"}, requirements={"id"="\d+"})
  307.      * @Template("Product/detail_app.twig")
  308.      * @ParamConverter("Product", options={"repository_method" = "findWithSortedClassCategories"})
  309.      */
  310.     public function detailApp(Request $requestProduct $Product)
  311.     {
  312.         if (!$this->checkVisibility($Product)) {
  313.             throw new NotFoundHttpException();
  314.         }
  315.         $builder $this->formFactory->createNamedBuilder(
  316.             '',
  317.             AddCartType::class,
  318.             null,
  319.             [
  320.                 'product' => $Product,
  321.                 'id_add_product_id' => false,
  322.             ]
  323.         );
  324.         $event = new EventArgs(
  325.             [
  326.                 'builder' => $builder,
  327.                 'Product' => $Product,
  328.             ],
  329.             $request
  330.         );
  331.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE);
  332.         $is_favorite false;
  333.         if ($this->isGranted('ROLE_USER')) {
  334.             $Customer $this->getUser();
  335.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  336.         }
  337.         return [
  338.             'title' => $this->title,
  339.             'subtitle' => $Product->getName(),
  340.             'form' => $builder->getForm()->createView(),
  341.             'Product' => $Product,
  342.             'is_favorite' => $is_favorite,
  343.         ];
  344.     }
  345.     /**
  346.      * お気に入り追加.
  347.      *
  348.      * @Route("/products/add_favorite/{id}", name="product_add_favorite", requirements={"id" = "\d+"}, methods={"GET", "POST"})
  349.      */
  350.     public function addFavorite(Request $requestProduct $Product)
  351.     {
  352.         $this->checkVisibility($Product);
  353.         $event = new EventArgs(
  354.             [
  355.                 'Product' => $Product,
  356.             ],
  357.             $request
  358.         );
  359.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_INITIALIZE);
  360.         if ($this->isGranted('ROLE_USER')) {
  361.             $Customer $this->getUser();
  362.             $this->customerFavoriteProductRepository->addFavorite($Customer$Product);
  363.             $this->session->getFlashBag()->set('product_detail.just_added_favorite'$Product->getId());
  364.             $event = new EventArgs(
  365.                 [
  366.                     'Product' => $Product,
  367.                 ],
  368.                 $request
  369.             );
  370.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  371.             return $this->redirectToRoute('product_detail', ['id' => $Product->getId()]);
  372.         } else {
  373.             // 非会員の場合、ログイン画面を表示
  374.             //  ログイン後の画面遷移先を設定
  375.             $this->setLoginTargetPath($this->generateUrl('product_add_favorite', ['id' => $Product->getId()], UrlGeneratorInterface::ABSOLUTE_URL));
  376.             $this->session->getFlashBag()->set('eccube.add.favorite'true);
  377.             $event = new EventArgs(
  378.                 [
  379.                     'Product' => $Product,
  380.                 ],
  381.                 $request
  382.             );
  383.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  384.             return $this->redirectToRoute('mypage_login');
  385.         }
  386.     }
  387.     /**
  388.      * お気に入り追加 スマホ用
  389.      *
  390.      * @Route("/products/add_favorite_app/{id}", name="product_add_favorite_app", requirements={"id" = "\d+"}, methods={"GET", "POST"})
  391.      */
  392.     public function addFavoriteApp(Request $requestProduct $Product)
  393.     {
  394.         $this->checkVisibility($Product);
  395.         $event = new EventArgs(
  396.             [
  397.                 'Product' => $Product,
  398.             ],
  399.             $request
  400.         );
  401.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_INITIALIZE);
  402.         if ($this->isGranted('ROLE_USER')) {
  403.             $Customer $this->getUser();
  404.             $this->customerFavoriteProductRepository->addFavorite($Customer$Product);
  405.             $this->session->getFlashBag()->set('product_detail.just_added_favorite'$Product->getId());
  406.             $event = new EventArgs(
  407.                 [
  408.                     'Product' => $Product,
  409.                 ],
  410.                 $request
  411.             );
  412.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  413.             return $this->redirectToRoute('product_detail_app', ['id' => $Product->getId()]);
  414.         } else {
  415.             // 非会員の場合、ログイン画面を表示
  416.             //  ログイン後の画面遷移先を設定
  417.             $this->setLoginTargetPath($this->generateUrl('product_add_favorite', ['id' => $Product->getId()], UrlGeneratorInterface::ABSOLUTE_URL));
  418.             $this->session->getFlashBag()->set('eccube.add.favorite'true);
  419.             $event = new EventArgs(
  420.                 [
  421.                     'Product' => $Product,
  422.                 ],
  423.                 $request
  424.             );
  425.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  426.             return $this->redirectToRoute('mypage_login');
  427.         }
  428.     }
  429.     /**
  430.      * カートに追加.
  431.      *
  432.      * @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
  433.      */
  434.     public function addCart(Request $requestProduct $Product)
  435.     {
  436.         // エラーメッセージの配列
  437.         $errorMessages = [];
  438.         if (!$this->checkVisibility($Product)) {
  439.             throw new NotFoundHttpException();
  440.         }
  441.         $builder $this->formFactory->createNamedBuilder(
  442.             '',
  443.             AddCartType::class,
  444.             null,
  445.             [
  446.                 'product' => $Product,
  447.                 'id_add_product_id' => false,
  448.             ]
  449.         );
  450.         $event = new EventArgs(
  451.             [
  452.                 'builder' => $builder,
  453.                 'Product' => $Product,
  454.             ],
  455.             $request
  456.         );
  457.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE);
  458.         /* @var $form \Symfony\Component\Form\FormInterface */
  459.         $form $builder->getForm();
  460.         $form->handleRequest($request);
  461.         if (!$form->isValid()) {
  462.             throw new NotFoundHttpException();
  463.         }
  464.         $addCartData $form->getData();
  465.         log_info(
  466.             'カート追加処理開始',
  467.             [
  468.                 'product_id' => $Product->getId(),
  469.                 'product_class_id' => $addCartData['product_class_id'],
  470.                 'quantity' => $addCartData['quantity'],
  471.             ]
  472.         );
  473.         // カートへ追加
  474.         $this->cartService->addProduct($addCartData['product_class_id'], $addCartData['quantity']);
  475.         // 明細の正規化
  476.         $Carts $this->cartService->getCarts();
  477.         foreach ($Carts as $Cart) {
  478.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  479.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  480.             if ($result->hasError()) {
  481.                 $this->cartService->removeProduct($addCartData['product_class_id']);
  482.                 foreach ($result->getErrors() as $error) {
  483.                     $errorMessages[] = $error->getMessage();
  484.                 }
  485.             }
  486.             foreach ($result->getWarning() as $warning) {
  487.                 $errorMessages[] = $warning->getMessage();
  488.             }
  489.         }
  490.         $this->cartService->save();
  491.         log_info(
  492.             'カート追加処理完了',
  493.             [
  494.                 'product_id' => $Product->getId(),
  495.                 'product_class_id' => $addCartData['product_class_id'],
  496.                 'quantity' => $addCartData['quantity'],
  497.             ]
  498.         );
  499.         $event = new EventArgs(
  500.             [
  501.                 'form' => $form,
  502.                 'Product' => $Product,
  503.             ],
  504.             $request
  505.         );
  506.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE);
  507.         if ($event->getResponse() !== null) {
  508.             return $event->getResponse();
  509.         }
  510.         if ($request->isXmlHttpRequest()) {
  511.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  512.             // 初期化
  513.             $messages = [];
  514.             if (empty($errorMessages)) {
  515.                 // エラーが発生していない場合
  516.                 $done true;
  517.                 array_push($messagestrans('front.product.add_cart_complete'));
  518.             } else {
  519.                 // エラーが発生している場合
  520.                 $done false;
  521.                 $messages $errorMessages;
  522.             }
  523.             return $this->json(['done' => $done'messages' => $messages]);
  524.         } else {
  525.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  526.             foreach ($errorMessages as $errorMessage) {
  527.                 $this->addRequestError($errorMessage);
  528.             }
  529.             return $this->redirectToRoute('cart');
  530.         }
  531.     }
  532.     /**
  533.      * ページタイトルの設定
  534.      *
  535.      * @param  array|null $searchData
  536.      *
  537.      * @return str
  538.      */
  539.     protected function getPageTitle($searchData)
  540.     {
  541.         if (isset($searchData['name']) && !empty($searchData['name'])) {
  542.             return trans('front.product.search_result');
  543.         } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
  544.             return $searchData['category_id']->getName();
  545.         } else {
  546.             return trans('front.product.all_products');
  547.         }
  548.     }
  549.     /**
  550.      * 閲覧可能な商品かどうかを判定
  551.      *
  552.      * @param Product $Product
  553.      *
  554.      * @return boolean 閲覧可能な場合はtrue
  555.      */
  556.     protected function checkVisibility(Product $Product)
  557.     {
  558.         $is_admin $this->session->has('_security_admin');
  559.         // 管理ユーザの場合はステータスやオプションにかかわらず閲覧可能.
  560.         if (!$is_admin) {
  561.             // 在庫なし商品の非表示オプションが有効な場合.
  562.             // if ($this->BaseInfo->isOptionNostockHidden()) {
  563.             //     if (!$Product->getStockFind()) {
  564.             //         return false;
  565.             //     }
  566.             // }
  567.             // 公開ステータスでない商品は表示しない.
  568.             if ($Product->getStatus()->getId() !== ProductStatus::DISPLAY_SHOW) {
  569.                 return false;
  570.             }
  571.         }
  572.         return true;
  573.     }
  574. }