src/Eccube/Controller/ProductController.php line 151

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. // CustomFieldsContentsRepository関連処理追加(C4M KIN)
  37. use Plugin\TabaCustomFields2\Repository\CustomFieldsContentsRepository;
  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.      * @param CustomFieldsContentsRepository $customFieldsContentsRepository
  80.      */
  81.     public function __construct(
  82.         PurchaseFlow $cartPurchaseFlow,
  83.         CustomerFavoriteProductRepository $customerFavoriteProductRepository,
  84.         CartService $cartService,
  85.         ProductRepository $productRepository,
  86.         BaseInfoRepository $baseInfoRepository,
  87.         AuthenticationUtils $helper,
  88.         ProductListMaxRepository $productListMaxRepository,
  89.         CustomFieldsContentsRepository $customFieldsContentsRepository
  90.     ) {
  91.         $this->purchaseFlow $cartPurchaseFlow;
  92.         $this->customerFavoriteProductRepository $customerFavoriteProductRepository;
  93.         $this->cartService $cartService;
  94.         $this->productRepository $productRepository;
  95.         $this->BaseInfo $baseInfoRepository->get();
  96.         $this->helper $helper;
  97.         $this->productListMaxRepository $productListMaxRepository;
  98.         $this->customFieldsContentsRepository $customFieldsContentsRepository;
  99.     }
  100.     /**
  101.      * 商品一覧画面.
  102.      *
  103.      * @Route("/products/list", name="product_list", methods={"GET"})
  104.      * @Template("Product/list.twig")
  105.      */
  106.     public function index(Request $requestPaginatorInterface $paginator)
  107.     {
  108.         // Doctrine SQLFilter
  109.         if ($this->BaseInfo->isOptionNostockHidden()) {
  110.             $this->entityManager->getFilters()->enable('option_nostock_hidden');
  111.         }
  112.         // handleRequestは空のqueryの場合は無視するため
  113.         if ($request->getMethod() === 'GET') {
  114.             $request->query->set('pageno'$request->query->get('pageno'''));
  115.         }
  116.         // searchForm
  117.         /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  118.         $builder $this->formFactory->createNamedBuilder(''SearchProductType::class);
  119.         if ($request->getMethod() === 'GET') {
  120.             $builder->setMethod('GET');
  121.         }
  122.         $event = new EventArgs(
  123.             [
  124.                 'builder' => $builder,
  125.             ],
  126.             $request
  127.         );
  128.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_INITIALIZE);
  129.         /* @var $searchForm \Symfony\Component\Form\FormInterface */
  130.         $searchForm $builder->getForm();
  131.         $searchForm->handleRequest($request);
  132.         // paginator
  133.         $searchData $searchForm->getData();
  134.         $qb $this->productRepository->getQueryBuilderBySearchData($searchData);
  135.         $event = new EventArgs(
  136.             [
  137.                 'searchData' => $searchData,
  138.                 'qb' => $qb,
  139.             ],
  140.             $request
  141.         );
  142.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_SEARCH);
  143.         $searchData $event->getArgument('searchData');
  144.         $query $qb->getQuery()
  145.             ->useResultCache(true$this->eccubeConfig['eccube_result_cache_lifetime_short']);
  146.         /** @var SlidingPagination $pagination */
  147.         $pagination $paginator->paginate(
  148.             $query,
  149.             !empty($searchData['pageno']) ? $searchData['pageno'] : 1,
  150.             !empty($searchData['disp_number']) ? $searchData['disp_number']->getId() : $this->productListMaxRepository->findOneBy([], ['sort_no' => 'ASC'])->getId()
  151.         );
  152.         $ids = [];
  153.         foreach ($pagination as $Product) {
  154.             $ids[] = $Product->getId();
  155.         }
  156.         $ProductsAndClassCategories $this->productRepository->findProductsWithSortedClassCategories($ids'p.id');
  157.         // addCart form
  158.         $forms = [];
  159.         foreach ($pagination as $Product) {
  160.             /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  161.             $builder $this->formFactory->createNamedBuilder(
  162.                 '',
  163.                 AddCartType::class,
  164.                 null,
  165.                 [
  166.                     'product' => $ProductsAndClassCategories[$Product->getId()],
  167.                     'allow_extra_fields' => true,
  168.                 ]
  169.             );
  170.             $addCartForm $builder->getForm();
  171.             $forms[$Product->getId()] = $addCartForm->createView();
  172.         }
  173.         $Category $searchForm->get('category_id')->getData();
  174.         return [
  175.             'subtitle' => $this->getPageTitle($searchData),
  176.             'pagination' => $pagination,
  177.             'search_form' => $searchForm->createView(),
  178.             'forms' => $forms,
  179.             'Category' => $Category,
  180.         ];
  181.     }
  182.     /**
  183.      * 商品詳細画面.
  184.      *
  185.      * @Route("/products/detail/{id}", name="product_detail", methods={"GET"}, requirements={"id" = "\d+"})
  186.      * @Template("Product/detail.twig")
  187.      * @ParamConverter("Product", options={"repository_method" = "findWithSortedClassCategories"})
  188.      *
  189.      * @param Request $request
  190.      * @param Product $Product
  191.      *
  192.      * @return array
  193.      */
  194.     public function detail(Request $requestProduct $Product)
  195.     {
  196.         // オリジナルURLがある場合リダイレクト(C4M KIN)
  197.         $ourl $this->customFieldsContentsRepository->getCustomFieldsContents("product"$Product->getId())->getPlgFieldContent4();
  198.         if ($ourl) {
  199.             return $this->redirect($ourl);
  200.         }
  201.         if (!$this->checkVisibility($Product)) {
  202.             throw new NotFoundHttpException();
  203.         }
  204.         $builder $this->formFactory->createNamedBuilder(
  205.             '',
  206.             AddCartType::class,
  207.             null,
  208.             [
  209.                 'product' => $Product,
  210.                 'id_add_product_id' => false,
  211.             ]
  212.         );
  213.         $event = new EventArgs(
  214.             [
  215.                 'builder' => $builder,
  216.                 'Product' => $Product,
  217.             ],
  218.             $request
  219.         );
  220.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE);
  221.         $is_favorite false;
  222.         if ($this->isGranted('ROLE_USER')) {
  223.             $Customer $this->getUser();
  224.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  225.         }
  226.         return [
  227.             'title' => $this->title,
  228.             'subtitle' => $Product->getName(),
  229.             'form' => $builder->getForm()->createView(),
  230.             'Product' => $Product,
  231.             'is_favorite' => $is_favorite,
  232.         ];
  233.     }
  234.     /**
  235.      * お気に入り追加.
  236.      *
  237.      * @Route("/products/add_favorite/{id}", name="product_add_favorite", requirements={"id" = "\d+"}, methods={"GET", "POST"})
  238.      */
  239.     public function addFavorite(Request $requestProduct $Product)
  240.     {
  241.         $this->checkVisibility($Product);
  242.         $event = new EventArgs(
  243.             [
  244.                 'Product' => $Product,
  245.             ],
  246.             $request
  247.         );
  248.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_INITIALIZE);
  249.         if ($this->isGranted('ROLE_USER')) {
  250.             $Customer $this->getUser();
  251.             $this->customerFavoriteProductRepository->addFavorite($Customer$Product);
  252.             $this->session->getFlashBag()->set('product_detail.just_added_favorite'$Product->getId());
  253.             $event = new EventArgs(
  254.                 [
  255.                     'Product' => $Product,
  256.                 ],
  257.                 $request
  258.             );
  259.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  260.             return $this->redirectToRoute('product_detail', ['id' => $Product->getId()]);
  261.         } else {
  262.             // 非会員の場合、ログイン画面を表示
  263.             //  ログイン後の画面遷移先を設定
  264.             $this->setLoginTargetPath($this->generateUrl('product_add_favorite', ['id' => $Product->getId()], UrlGeneratorInterface::ABSOLUTE_URL));
  265.             $this->session->getFlashBag()->set('eccube.add.favorite'true);
  266.             $event = new EventArgs(
  267.                 [
  268.                     'Product' => $Product,
  269.                 ],
  270.                 $request
  271.             );
  272.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  273.             return $this->redirectToRoute('mypage_login');
  274.         }
  275.     }
  276.     /**
  277.      * カートに追加.
  278.      *
  279.      * @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
  280.      */
  281.     public function addCart(Request $requestProduct $Product)
  282.     {
  283.         // エラーメッセージの配列
  284.         $errorMessages = [];
  285.         if (!$this->checkVisibility($Product)) {
  286.             throw new NotFoundHttpException();
  287.         }
  288.         $builder $this->formFactory->createNamedBuilder(
  289.             '',
  290.             AddCartType::class,
  291.             null,
  292.             [
  293.                 'product' => $Product,
  294.                 'id_add_product_id' => false,
  295.             ]
  296.         );
  297.         $event = new EventArgs(
  298.             [
  299.                 'builder' => $builder,
  300.                 'Product' => $Product,
  301.             ],
  302.             $request
  303.         );
  304.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE);
  305.         /* @var $form \Symfony\Component\Form\FormInterface */
  306.         $form $builder->getForm();
  307.         $form->handleRequest($request);
  308.         if (!$form->isValid()) {
  309.             throw new NotFoundHttpException();
  310.         }
  311.         $addCartData $form->getData();
  312.         log_info(
  313.             'カート追加処理開始',
  314.             [
  315.                 'product_id' => $Product->getId(),
  316.                 'product_class_id' => $addCartData['product_class_id'],
  317.                 'quantity' => $addCartData['quantity'],
  318.             ]
  319.         );
  320.         // カートへ追加
  321.         $this->cartService->addProduct($addCartData['product_class_id'], $addCartData['quantity']);
  322.         // 明細の正規化
  323.         $Carts $this->cartService->getCarts();
  324.         foreach ($Carts as $Cart) {
  325.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  326.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  327.             if ($result->hasError()) {
  328.                 $this->cartService->removeProduct($addCartData['product_class_id']);
  329.                 foreach ($result->getErrors() as $error) {
  330.                     $errorMessages[] = $error->getMessage();
  331.                 }
  332.             }
  333.             foreach ($result->getWarning() as $warning) {
  334.                 $errorMessages[] = $warning->getMessage();
  335.             }
  336.         }
  337.         $this->cartService->save();
  338.         log_info(
  339.             'カート追加処理完了',
  340.             [
  341.                 'product_id' => $Product->getId(),
  342.                 'product_class_id' => $addCartData['product_class_id'],
  343.                 'quantity' => $addCartData['quantity'],
  344.             ]
  345.         );
  346.         $event = new EventArgs(
  347.             [
  348.                 'form' => $form,
  349.                 'Product' => $Product,
  350.             ],
  351.             $request
  352.         );
  353.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE);
  354.         if ($event->getResponse() !== null) {
  355.             return $event->getResponse();
  356.         }
  357.         if ($request->isXmlHttpRequest()) {
  358.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  359.             // 初期化
  360.             $messages = [];
  361.             if (empty($errorMessages)) {
  362.                 // エラーが発生していない場合
  363.                 $done true;
  364.                 array_push($messagestrans('front.product.add_cart_complete'));
  365.             } else {
  366.                 // エラーが発生している場合
  367.                 $done false;
  368.                 $messages $errorMessages;
  369.             }
  370.             return $this->json(['done' => $done'messages' => $messages]);
  371.         } else {
  372.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  373.             foreach ($errorMessages as $errorMessage) {
  374.                 $this->addRequestError($errorMessage);
  375.             }
  376.             return $this->redirectToRoute('cart');
  377.         }
  378.     }
  379.     /**
  380.      * ページタイトルの設定
  381.      *
  382.      * @param  array|null $searchData
  383.      *
  384.      * @return str
  385.      */
  386.     protected function getPageTitle($searchData)
  387.     {
  388.         if (isset($searchData['name']) && !empty($searchData['name'])) {
  389.             return trans('front.product.search_result');
  390.         } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
  391.             return $searchData['category_id']->getName();
  392.         } else {
  393.             return trans('front.product.all_products');
  394.         }
  395.     }
  396.     /**
  397.      * 閲覧可能な商品かどうかを判定
  398.      *
  399.      * @param Product $Product
  400.      *
  401.      * @return boolean 閲覧可能な場合はtrue
  402.      */
  403.     protected function checkVisibility(Product $Product)
  404.     {
  405.         $is_admin $this->session->has('_security_admin');
  406.         // 管理ユーザの場合はステータスやオプションにかかわらず閲覧可能.
  407.         if (!$is_admin) {
  408.             // 在庫なし商品の非表示オプションが有効な場合.
  409.             // if ($this->BaseInfo->isOptionNostockHidden()) {
  410.             //     if (!$Product->getStockFind()) {
  411.             //         return false;
  412.             //     }
  413.             // }
  414.             // 公開ステータスでない商品は表示しない.
  415.             if ($Product->getStatus()->getId() !== ProductStatus::DISPLAY_SHOW) {
  416.                 return false;
  417.             }
  418.         }
  419.         return true;
  420.     }
  421. }