src/Eccube/Controller/ProductController.php line 258

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