src/Eccube/Controller/ProductController.php line 518

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\Category;
  15. use Eccube\Entity\Master\ProductStatus;
  16. use Eccube\Entity\Product;
  17. use Eccube\Entity\ProductCategory;
  18. use Eccube\Event\EccubeEvents;
  19. use Eccube\Event\EventArgs;
  20. use Eccube\Form\Type\AddCartType;
  21. use Eccube\Form\Type\SearchProductType;
  22. use Eccube\Repository\BaseInfoRepository;
  23. use Eccube\Repository\CategoryRepository;
  24. use Eccube\Repository\CustomerFavoriteProductRepository;
  25. use Eccube\Repository\Master\ProductListMaxRepository;
  26. use Eccube\Repository\ProductRepository;
  27. use Eccube\Service\CartService;
  28. use Eccube\Service\PurchaseFlow\PurchaseContext;
  29. use Eccube\Service\PurchaseFlow\PurchaseFlow;
  30. use Knp\Bundle\PaginatorBundle\Pagination\SlidingPagination;
  31. use Knp\Component\Pager\PaginatorInterface;
  32. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  33. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  34. use Symfony\Component\HttpFoundation\Request;
  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.     /**
  71.      * ProductController constructor.
  72.      *
  73.      * @param PurchaseFlow $cartPurchaseFlow
  74.      * @param CustomerFavoriteProductRepository $customerFavoriteProductRepository
  75.      * @param CartService $cartService
  76.      * @param ProductRepository $productRepository
  77.      * @param BaseInfoRepository $baseInfoRepository
  78.      * @param AuthenticationUtils $helper
  79.      * @param ProductListMaxRepository $productListMaxRepository
  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.         CategoryRepository $categoryRepository
  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->categoryRepository $categoryRepository;
  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.         $category_id $searchForm->get('category_id');
  133.         if (is_null($category_id->getData())) {
  134.             return $this->redirectToRoute('homepage');
  135.         };
  136.         // paginator
  137.         $searchData $searchForm->getData();
  138.         $qb $this->productRepository->getQueryBuilderBySearchData($searchData);
  139.         $event = new EventArgs(
  140.             [
  141.                 'searchData' => $searchData,
  142.                 'qb' => $qb,
  143.             ],
  144.             $request
  145.         );
  146.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_SEARCH);
  147.         $searchData $event->getArgument('searchData');
  148.         $query $qb->getQuery()
  149.             ->useResultCache(true$this->eccubeConfig['eccube_result_cache_lifetime_short']);
  150.         /** @var SlidingPagination $pagination */
  151.         $pagination $paginator->paginate(
  152.             $query,
  153.             !empty($searchData['pageno']) ? $searchData['pageno'] : 1,
  154.             !empty($searchData['disp_number']) ? $searchData['disp_number']->getId() : $this->productListMaxRepository->findOneBy([], ['sort_no' => 'ASC'])->getId()
  155.         );
  156.         $ids = [];
  157.         foreach ($pagination as $Product) {
  158.             $ids[] = $Product->getId();
  159.         }
  160.         $ProductsAndClassCategories $this->productRepository->findProductsWithSortedClassCategories($ids'p.id');
  161.         // addCart form
  162.         $forms = [];
  163.         foreach ($pagination as $Product) {
  164.             /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  165.             $builder $this->formFactory->createNamedBuilder(
  166.                 '',
  167.                 AddCartType::class,
  168.                 null,
  169.                 [
  170.                     'product' => $ProductsAndClassCategories[$Product->getId()],
  171.                     'allow_extra_fields' => true,
  172.                 ]
  173.             );
  174.             $addCartForm $builder->getForm();
  175.             $forms[$Product->getId()] = $addCartForm->createView();
  176.         }
  177.         $Category $searchForm->get('category_id')->getData();
  178.         return [
  179.             'subtitle' => $this->getPageTitle($searchData),
  180.             'pagination' => $pagination,
  181.             'search_form' => $searchForm->createView(),
  182.             'forms' => $forms,
  183.             'Category' => $Category,
  184.         ];
  185.     }
  186.     /**
  187.      * 商品詳細画面.
  188.      *
  189.      * @Route("/products/detail/{id}", name="product_detail", methods={"GET"}, requirements={"id" = "\d+"})
  190.      * @Template("Product/detail.twig")
  191.      * @ParamConverter("Product", options={"repository_method" = "findWithSortedClassCategories"})
  192.      *
  193.      * @param Request $request
  194.      * @param Product $Product
  195.      *
  196.      * @return array
  197.      */
  198.     public function detail(Request $requestProduct $Product)
  199.     {
  200.         if (!$this->checkVisibility($Product)) {
  201.             throw new NotFoundHttpException();
  202.         }
  203.         $builder $this->formFactory->createNamedBuilder(
  204.             '',
  205.             AddCartType::class,
  206.             null,
  207.             [
  208.                 'product' => $Product,
  209.                 'id_add_product_id' => false,
  210.             ]
  211.         );
  212.         $event = new EventArgs(
  213.             [
  214.                 'builder' => $builder,
  215.                 'Product' => $Product,
  216.             ],
  217.             $request
  218.         );
  219.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE);
  220.         $is_favorite false;
  221.         if ($this->isGranted('ROLE_USER')) {
  222.             $Customer $this->getUser();
  223.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  224.         }
  225.         // 商品に紐づくカテゴリを親カテゴリと小カテゴリに分けてtwigに渡す
  226.         $Categories $this->categoryRepository->findAll();
  227.         $ProductCategories $Product->getProductCategories();
  228.         $mainCategoryIds = [];
  229.         $childCategoryIds = [];
  230.         foreach($Categories as $Category){
  231.             if (count($Category->getChildren()) > 0){
  232.                 array_push($mainCategoryIds,$Category->getId());
  233.             } else {
  234.                 array_push($childCategoryIds,$Category->getId());
  235.             }
  236.         }
  237.         $Category null;
  238.         $childCategory null;
  239.         if (count($Categories) > 0) {
  240.             foreach($ProductCategories as $ProductCategory) {
  241.                 $checkCategory $ProductCategory->getCategory();
  242.                 if (in_array($checkCategory->getId(),$mainCategoryIds)) {
  243.                     $Category $checkCategory;
  244.                     break;
  245.                 }
  246.             }
  247.             foreach($ProductCategories as $ProductCategory) {
  248.                 $checkCategory $ProductCategory->getCategory();
  249.                 if (in_array($checkCategory->getId(),$childCategoryIds)) {
  250.                     $childCategory $checkCategory;
  251.                     break;
  252.                 }
  253.             }
  254.         }
  255.         $ProductCategoryIds = [];
  256.         foreach($Product->getProductCategories() as $ProductCategory){
  257.             array_push($ProductCategoryIds,$ProductCategory->getCategoryId());
  258.         }
  259.         return [
  260.             'title' => $this->title,
  261.             'subtitle' => $Product->getName(),
  262.             'form' => $builder->getForm()->createView(),
  263.             'Product' => $Product,
  264.             'ProductCategoryIds' => $ProductCategoryIds,
  265.             'productOptionId' => $Product->getProductOptions()[1] ? $Product->getProductOptions()[1]->getOption()->getId() : "",
  266.             'productOptionSecondId' => $Product->getId() == Product::KAKEIHAI $Product->getProductOptions()[0]->getOption()->getId() : "",
  267.             'is_favorite' => $is_favorite,
  268.             'Categories' => [
  269.                 'Category' => $Category,
  270.             ],
  271.             'parentCategoryIds' =>[
  272.                 Category::OIHAI,
  273.                 Category::OBUTSUDAN_KUYOUDAI,
  274.                 Category::BUTSUGU_SET,
  275.                 Category::BUTSUGU_OTHER,
  276.                 Category::TEMOTO_KUYOU,
  277.             ],
  278.         ];
  279.     }
  280.     /**
  281.      * お気に入り追加.
  282.      *
  283.      * @Route("/products/add_favorite/{id}", name="product_add_favorite", requirements={"id" = "\d+"}, methods={"GET", "POST"})
  284.      */
  285.     public function addFavorite(Request $requestProduct $Product)
  286.     {
  287.         $this->checkVisibility($Product);
  288.         $event = new EventArgs(
  289.             [
  290.                 'Product' => $Product,
  291.             ],
  292.             $request
  293.         );
  294.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_INITIALIZE);
  295.         if ($this->isGranted('ROLE_USER')) {
  296.             $Customer $this->getUser();
  297.             $this->customerFavoriteProductRepository->addFavorite($Customer$Product);
  298.             $this->session->getFlashBag()->set('product_detail.just_added_favorite'$Product->getId());
  299.             $event = new EventArgs(
  300.                 [
  301.                     'Product' => $Product,
  302.                 ],
  303.                 $request
  304.             );
  305.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  306.             return $this->redirectToRoute('product_detail', ['id' => $Product->getId()]);
  307.         } else {
  308.             // 非会員の場合、ログイン画面を表示
  309.             //  ログイン後の画面遷移先を設定
  310.             $this->setLoginTargetPath($this->generateUrl('product_add_favorite', ['id' => $Product->getId()], UrlGeneratorInterface::ABSOLUTE_URL));
  311.             $this->session->getFlashBag()->set('eccube.add.favorite'true);
  312.             $event = new EventArgs(
  313.                 [
  314.                     'Product' => $Product,
  315.                 ],
  316.                 $request
  317.             );
  318.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  319.             return $this->redirectToRoute('mypage_login');
  320.         }
  321.     }
  322.     /**
  323.      * カートに追加.
  324.      *
  325.      * @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
  326.      */
  327.     public function addCart(Request $requestProduct $Product)
  328.     {
  329.         // エラーメッセージの配列
  330.         $errorMessages = [];
  331.         if (!$this->checkVisibility($Product)) {
  332.             throw new NotFoundHttpException();
  333.         }
  334.         $builder $this->formFactory->createNamedBuilder(
  335.             '',
  336.             AddCartType::class,
  337.             null,
  338.             [
  339.                 'product' => $Product,
  340.                 'id_add_product_id' => false,
  341.             ]
  342.         );
  343.         $event = new EventArgs(
  344.             [
  345.                 'builder' => $builder,
  346.                 'Product' => $Product,
  347.             ],
  348.             $request
  349.         );
  350.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE);
  351.         /* @var $form \Symfony\Component\Form\FormInterface */
  352.         $form $builder->getForm();
  353.         $form->handleRequest($request);
  354.         if (!$form->isValid()) {
  355.             throw new NotFoundHttpException();
  356.         }
  357.         $addCartData $form->getData();
  358.         log_info(
  359.             'カート追加処理開始',
  360.             [
  361.                 'product_id' => $Product->getId(),
  362.                 'product_class_id' => $addCartData['product_class_id'],
  363.                 'quantity' => $addCartData['quantity'],
  364.                 'naire' => $addCartData['naire'],
  365.             ]
  366.         );
  367.         // カートへ追加
  368.         $this->cartService->addProduct($addCartData['product_class_id'], $addCartData['quantity'], $addCartData['naire']);
  369.         // 明細の正規化
  370.         $Carts $this->cartService->getCarts();
  371.         foreach ($Carts as $Cart) {
  372.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  373.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  374.             if ($result->hasError()) {
  375.                 $this->cartService->removeProduct($addCartData['product_class_id']);
  376.                 foreach ($result->getErrors() as $error) {
  377.                     $errorMessages[] = $error->getMessage();
  378.                 }
  379.             }
  380.             foreach ($result->getWarning() as $warning) {
  381.                 $errorMessages[] = $warning->getMessage();
  382.             }
  383.         }
  384.         $this->cartService->save();
  385.         log_info(
  386.             'カート追加処理完了',
  387.             [
  388.                 'product_id' => $Product->getId(),
  389.                 'product_class_id' => $addCartData['product_class_id'],
  390.                 'quantity' => $addCartData['quantity'],
  391.                 'naire' => $addCartData['naire'],
  392.             ]
  393.         );
  394.         $event = new EventArgs(
  395.             [
  396.                 'form' => $form,
  397.                 'Product' => $Product,
  398.             ],
  399.             $request
  400.         );
  401.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE);
  402.         if ($event->getResponse() !== null) {
  403.             return $event->getResponse();
  404.         }
  405.         if ($request->isXmlHttpRequest()) {
  406.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  407.             // 初期化
  408.             $messages = [];
  409.             if (empty($errorMessages)) {
  410.                 // エラーが発生していない場合
  411.                 $done true;
  412.                 array_push($messagestrans('front.product.add_cart_complete'));
  413.             } else {
  414.                 // エラーが発生している場合
  415.                 $done false;
  416.                 $messages $errorMessages;
  417.             }
  418.             return $this->json(['done' => $done'messages' => $messages]);
  419.         } else {
  420.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  421.             foreach ($errorMessages as $errorMessage) {
  422.                 $this->addRequestError($errorMessage);
  423.             }
  424.             return $this->redirectToRoute('cart');
  425.         }
  426.     }
  427.     /**
  428.      * ページタイトルの設定
  429.      *
  430.      * @param  array|null $searchData
  431.      *
  432.      * @return str
  433.      */
  434.     protected function getPageTitle($searchData)
  435.     {
  436.         if (isset($searchData['name']) && !empty($searchData['name'])) {
  437.             return trans('front.product.search_result');
  438.         } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
  439.             return $searchData['category_id']->getName();
  440.         } else {
  441.             return trans('front.product.all_products');
  442.         }
  443.     }
  444.     /**
  445.      * 閲覧可能な商品かどうかを判定
  446.      *
  447.      * @param Product $Product
  448.      *
  449.      * @return boolean 閲覧可能な場合はtrue
  450.      */
  451.     protected function checkVisibility(Product $Product)
  452.     {
  453.         $is_admin $this->session->has('_security_admin');
  454.         // 管理ユーザの場合はステータスやオプションにかかわらず閲覧可能.
  455.         if (!$is_admin) {
  456.             // 在庫なし商品の非表示オプションが有効な場合.
  457.             // if ($this->BaseInfo->isOptionNostockHidden()) {
  458.             //     if (!$Product->getStockFind()) {
  459.             //         return false;
  460.             //     }
  461.             // }
  462.             // 公開ステータスでない商品は表示しない.
  463.             if ($Product->getStatus()->getId() !== ProductStatus::DISPLAY_SHOW) {
  464.                 return false;
  465.             }
  466.         }
  467.         return true;
  468.     }
  469. }