src/Eccube/Controller/ProductController.php line 280

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