src/Eccube/Controller/ProductController.php line 371

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(findProductsWithSortedClassCategories は表示可能規格+ProductStock のみのため、一覧クエリと一致しないIDはスキップ)
  210.         $forms = [];
  211.         foreach ($pagination as $Product) {
  212.             $productId $Product->getId();
  213.             if (!isset($ProductsAndClassCategories[$productId])) {
  214.                 continue;
  215.             }
  216.             /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  217.             $builder $this->formFactory->createNamedBuilder(
  218.                 '',
  219.                 AddCartType::class,
  220.                 null,
  221.                 [
  222.                     'product' => $ProductsAndClassCategories[$productId],
  223.                     'allow_extra_fields' => true,
  224.                 ]
  225.             );
  226.             $addCartForm $builder->getForm();
  227.             $forms[$productId] = $addCartForm->createView();
  228.         }
  229.         $keyword $searchForm->get('keyword')->getData();
  230.         if ($keyword) {        
  231.             $qb->andWhere('p.name LIKE :keyword OR p.actress LIKE :keyword OR m.name LIKE :keyword')
  232.             ->setParameter('keyword''%' $keyword '%');
  233.         }
  234.         
  235.         /*
  236.         $is_favorite = false;
  237.         if ($this->isGranted('ROLE_USER')) {
  238.             $Customer = $this->getUser();
  239.             $is_favorite = $this->customerFavoriteProductRepository->isFavorite($Customer, $Product);
  240.         }
  241.         */
  242.         return [
  243.             'subtitle' => $this->getPageTitle($searchData),
  244.             'pagination' => $pagination,
  245.             'search_form' => $searchForm->createView(), 
  246.             'forms' => $forms
  247.         ];
  248.     }
  249.     /**
  250.      * 商品詳細画面.
  251.      *
  252.      * @Route("/products/detail/{id}", name="product_detail", methods={"GET"}, requirements={"id" = "\d+"})
  253.      * @Template("Product/detail.twig")
  254.      * @ParamConverter("Product", options={"repository_method" = "findWithSortedClassCategories"})
  255.      *
  256.      * @param Request $request
  257.      * @param Product $Product
  258.      *
  259.      * @return array
  260.      */
  261.     public function detail(Request $requestProduct $Product)
  262.     {
  263.         if (!$this->checkVisibility($Product)) {
  264.             throw new NotFoundHttpException();
  265.         }
  266.         $builder $this->formFactory->createNamedBuilder(
  267.             '',
  268.             AddCartType::class,
  269.             null,
  270.             [
  271.                 'product' => $Product,
  272.                 'id_add_product_id' => false,
  273.             ]
  274.         );
  275.         $event = new EventArgs(
  276.             [
  277.                 'builder' => $builder,
  278.                 'Product' => $Product,
  279.             ],
  280.             $request
  281.         );
  282.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE);
  283.         $is_favorite false;
  284.         if ($this->isGranted('ROLE_USER')) {
  285.             $Customer $this->getUser();
  286.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  287.         }
  288.         // 関連商品(同一メーカーからランダム5件)
  289.         $makerId null;
  290.         if (method_exists($Product'getMaker') && $Product->getMaker()) {
  291.             $makerId $Product->getMaker()->getId();
  292.         }
  293.         $RelatedProducts $this->productRepository->findRandomByMaker($makerId5$Product->getId());
  294.         // よく見られる商品(管理で設定、ランダム5件)
  295.         $popularProductIds $this->relatedProductSettingRepository->findRandomProductIds(5);
  296.         $PopularProducts = [];
  297.         if (!empty($popularProductIds)) {
  298.             $PopularProducts $this->productRepository->findBy(
  299.                 ['id' => $popularProductIds'Status' => \Eccube\Entity\Master\ProductStatus::DISPLAY_SHOW],
  300.                 ['id' => 'DESC']
  301.             );
  302.         }
  303.         return [
  304.             'title' => $this->title,
  305.             'subtitle' => $Product->getName(),
  306.             'form' => $builder->getForm()->createView(),
  307.             'Product' => $Product,
  308.             'favorite' => $is_favorite,
  309.             'RelatedProducts' => $RelatedProducts,
  310.             'PopularProducts' => $PopularProducts,
  311.         ];
  312.     }
  313.     /**
  314.      * お気に入り追加.
  315.      *
  316.      * @Route("/products/add_favorite/{id}", name="product_add_favorite", requirements={"id" = "\d+"}, methods={"GET", "POST"})
  317.      */
  318.     public function addFavorite(Request $requestProduct $Product)
  319.     {
  320.         $this->checkVisibility($Product);
  321.         $event = new EventArgs(
  322.             [
  323.                 'Product' => $Product,
  324.             ],
  325.             $request
  326.         );
  327.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_INITIALIZE);
  328.         if ($this->isGranted('ROLE_USER')) {
  329.             $Customer $this->getUser();
  330.             $this->customerFavoriteProductRepository->addFavorite($Customer$Product);
  331.             $this->session->getFlashBag()->set('product_detail.just_added_favorite'$Product->getId());
  332.             $event = new EventArgs(
  333.                 [
  334.                     'Product' => $Product,
  335.                 ],
  336.                 $request
  337.             );
  338.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  339.             return $this->redirectToRoute('product_detail', ['id' => $Product->getId()]);
  340.         } else {
  341.             // 非会員の場合、ログイン画面を表示
  342.             //  ログイン後の画面遷移先を設定
  343.             $this->setLoginTargetPath($this->generateUrl('product_add_favorite', ['id' => $Product->getId()], UrlGeneratorInterface::ABSOLUTE_URL));
  344.             $this->session->getFlashBag()->set('eccube.add.favorite'true);
  345.             $event = new EventArgs(
  346.                 [
  347.                     'Product' => $Product,
  348.                 ],
  349.                 $request
  350.             );
  351.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  352.             return $this->redirectToRoute('mypage_login');
  353.         }
  354.     }
  355.     /**
  356.      * カートに追加.
  357.      *
  358.      * @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
  359.      */
  360.     public function addCart(Request $requestProduct $Product)
  361.     {
  362.         // エラーメッセージの配列
  363.         $errorMessages = [];
  364.         if (!$this->checkVisibility($Product)) {
  365.             throw new NotFoundHttpException();
  366.         }
  367.         $builder $this->formFactory->createNamedBuilder(
  368.             '',
  369.             AddCartType::class,
  370.             null,
  371.             [
  372.                 'product' => $Product,
  373.                 'id_add_product_id' => false,
  374.             ]
  375.         );
  376.         $event = new EventArgs(
  377.             [
  378.                 'builder' => $builder,
  379.                 'Product' => $Product,
  380.             ],
  381.             $request
  382.         );
  383.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE);
  384.         /* @var $form \Symfony\Component\Form\FormInterface */
  385.         $form $builder->getForm();
  386.         $form->handleRequest($request);
  387.         if (!$form->isValid()) {
  388.             throw new NotFoundHttpException();
  389.         }
  390.         $addCartData $form->getData();
  391.         log_info(
  392.             'カート追加処理開始',
  393.             [
  394.                 'product_id' => $Product->getId(),
  395.                 'product_class_id' => $addCartData['product_class_id'],
  396.                 'quantity' => $addCartData['quantity'],
  397.             ]
  398.         );
  399.         $productClassId $request->get('ProductClass');
  400.         // カートへ追加
  401.         $this->cartService->addProduct($addCartData['product_class_id'], $addCartData['quantity']);
  402.         // 明細の正規化
  403.         $Carts $this->cartService->getCarts();
  404.         foreach ($Carts as $Cart) {
  405.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  406.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  407.             if ($result->hasError()) {
  408.                 $this->cartService->removeProduct($addCartData['product_class_id']);
  409.                 foreach ($result->getErrors() as $error) {
  410.                     $errorMessages[] = $error->getMessage();
  411.                 }
  412.             }
  413.             foreach ($result->getWarning() as $warning) {
  414.                 $errorMessages[] = $warning->getMessage();
  415.             }
  416.         }
  417.         $this->cartService->save();
  418.         log_info(
  419.             'カート追加処理完了',
  420.             [
  421.                 'product_id' => $Product->getId(),
  422.                 'product_class_id' => $addCartData['product_class_id'],
  423.                 'quantity' => $addCartData['quantity'],
  424.             ]
  425.         );
  426.         $event = new EventArgs(
  427.             [
  428.                 'form' => $form,
  429.                 'Product' => $Product,
  430.             ],
  431.             $request
  432.         );
  433.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE);
  434.         if ($event->getResponse() !== null) {
  435.             return $event->getResponse();
  436.         }
  437.         if ($request->isXmlHttpRequest()) {
  438.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  439.             // 初期化
  440.             $messages = [];
  441.             if (empty($errorMessages)) {
  442.                 // エラーが発生していない場合
  443.                 $done true;
  444.                 array_push($messagestrans('front.product.add_cart_complete'));
  445.             } else {
  446.                 // エラーが発生している場合
  447.                 $done false;
  448.                 $messages $errorMessages;
  449.             }
  450.             return $this->json(['done' => $done'messages' => $messages]);
  451.         } else {
  452.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  453.             foreach ($errorMessages as $errorMessage) {
  454.                 $this->addRequestError($errorMessage);
  455.             }
  456.             return $this->redirectToRoute('cart');
  457.         }
  458.     }
  459.     /**
  460.      * ページタイトルの設定
  461.      *
  462.      * @param  array|null $searchData
  463.      *
  464.      * @return str
  465.      */
  466.     protected function getPageTitle($searchData)
  467.     {
  468.         if (isset($searchData['name']) && !empty($searchData['name'])) {
  469.             return trans('front.product.search_result');
  470.         } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
  471.             return $searchData['category_id']->getName();
  472.         } else {
  473.             return trans('front.product.all_products');
  474.         }
  475.     }
  476.     /**
  477.      * 閲覧可能な商品かどうかを判定
  478.      *
  479.      * @param Product $Product
  480.      *
  481.      * @return boolean 閲覧可能な場合はtrue
  482.      */
  483.     protected function checkVisibility(Product $Product)
  484.     {
  485.         $is_admin $this->session->has('_security_admin');
  486.         // 管理ユーザの場合はステータスやオプションにかかわらず閲覧可能.
  487.         if (!$is_admin) {
  488.             // 在庫なし商品の非表示オプションが有効な場合.
  489.             // if ($this->BaseInfo->isOptionNostockHidden()) {
  490.             //     if (!$Product->getStockFind()) {
  491.             //         return false;
  492.             //     }
  493.             // }
  494.             // 公開ステータスでない商品は表示しない.
  495.             if ($Product->getStatus()->getId() !== ProductStatus::DISPLAY_SHOW) {
  496.                 return false;
  497.             }
  498.         }
  499.         return true;
  500.     }
  501. }