app/Customize/Controller/ProductController.php line 130

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