app/Customize/Controller/ProductController.php line 124

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