app/Customize/Controller/ProductController.php line 189

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