app/Customize/Controller/CustomProductController.php line 116

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\Entity\Delivery;
  18. use Eccube\Event\EccubeEvents;
  19. use Eccube\Event\EventArgs;
  20. use Eccube\Form\Type\AddCartType;
  21. use Eccube\Form\Type\SearchProductType;
  22. use Eccube\Repository\BaseInfoRepository;
  23. use Eccube\Repository\CustomerFavoriteProductRepository;
  24. use Eccube\Repository\Master\ProductListMaxRepository;
  25. use Eccube\Repository\ProductRepository;
  26. use Eccube\Service\CartService;
  27. use Eccube\Service\PurchaseFlow\PurchaseContext;
  28. use Eccube\Service\PurchaseFlow\PurchaseFlow;
  29. use Knp\Bundle\PaginatorBundle\Pagination\SlidingPagination;
  30. use Knp\Component\Pager\PaginatorInterface;
  31. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  32. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  33. use Symfony\Component\HttpFoundation\Request;
  34. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  35. use Symfony\Component\Routing\Annotation\Route;
  36. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  37. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  38. class CustomProductController 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.     private $title '';
  69.     /**
  70.      * ProductController constructor.
  71.      *
  72.      * @param PurchaseFlow $cartPurchaseFlow
  73.      * @param CustomerFavoriteProductRepository $customerFavoriteProductRepository
  74.      * @param CartService $cartService
  75.      * @param ProductRepository $productRepository
  76.      * @param BaseInfoRepository $baseInfoRepository
  77.      * @param AuthenticationUtils $helper
  78.      * @param ProductListMaxRepository $productListMaxRepository
  79.      */
  80.     public function __construct(
  81.         PurchaseFlow $cartPurchaseFlow,
  82.         CustomerFavoriteProductRepository $customerFavoriteProductRepository,
  83.         CartService $cartService,
  84.         ProductRepository $productRepository,
  85.         BaseInfoRepository $baseInfoRepository,
  86.         AuthenticationUtils $helper,
  87.         ProductListMaxRepository $productListMaxRepository
  88.     ) {
  89.         $this->purchaseFlow $cartPurchaseFlow;
  90.         $this->customerFavoriteProductRepository $customerFavoriteProductRepository;
  91.         $this->cartService $cartService;
  92.         $this->productRepository $productRepository;
  93.         $this->BaseInfo $baseInfoRepository->get();
  94.         $this->helper $helper;
  95.         $this->productListMaxRepository $productListMaxRepository;
  96.     }
  97.     /**
  98.      * 商品一覧画面.
  99.      *
  100.      * @Route("/products/list", name="product_list", methods={"GET"})
  101.      * @Template("Product/list.twig")
  102.      */
  103.     public function index(Request $requestPaginatorInterface $paginator)
  104.     {
  105.         // Doctrine SQLFilter
  106.         if ($this->BaseInfo->isOptionNostockHidden()) {
  107.             $this->entityManager->getFilters()->enable('option_nostock_hidden');
  108.         }
  109.         // handleRequestは空のqueryの場合は無視するため
  110.         if ($request->getMethod() === 'GET') {
  111.             $request->query->set('pageno'$request->query->get('pageno'''));
  112.         }
  113.         // searchForm
  114.         /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  115.         $builder $this->formFactory->createNamedBuilder(''SearchProductType::class);
  116.         if ($request->getMethod() === 'GET') {
  117.             $builder->setMethod('GET');
  118.         }
  119.         $event = new EventArgs(
  120.             [
  121.                 'builder' => $builder,
  122.             ],
  123.             $request
  124.         );
  125.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_INITIALIZE);
  126.         /* @var $searchForm \Symfony\Component\Form\FormInterface */
  127.         $searchForm $builder->getForm();
  128.         $searchForm->handleRequest($request);
  129.         // paginator
  130.         $searchData $searchForm->getData();
  131.         $qb $this->productRepository->getQueryBuilderBySearchData($searchData);
  132.         // is_hiddenフラグで非表示商品を除外
  133.         $qb->andWhere('p.is_hidden = :is_hidden OR p.is_hidden IS NULL')
  134.            ->setParameter('is_hidden'false);
  135.         $event = new EventArgs(
  136.             [
  137.                 'searchData' => $searchData,
  138.                 'qb' => $qb,
  139.             ],
  140.             $request
  141.         );
  142.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_SEARCH);
  143.         $searchData $event->getArgument('searchData');
  144.         $query $qb->getQuery()
  145.             ->useResultCache(true$this->eccubeConfig['eccube_result_cache_lifetime_short']);
  146.         /** @var SlidingPagination $pagination */
  147.         $pagination $paginator->paginate(
  148.             $query,
  149.             !empty($searchData['pageno']) ? $searchData['pageno'] : 1,
  150.             !empty($searchData['disp_number']) ? $searchData['disp_number']->getId() : $this->productListMaxRepository->findOneBy([], ['sort_no' => 'ASC'])->getId()
  151.         );
  152.         // 定期購入商品を優先的にソート
  153.         $products = [];
  154.         foreach ($pagination as $Product) {
  155.             $products[] = $Product;
  156.         }
  157.         // subscriptionフィールドで昇順ソート(定期購入商品を後に)
  158.         usort($products, function($a$b) {
  159.             // subscription がtrueの場合は1、falseの場合は0として比較
  160.             $aSubscription $a->subscription 0;
  161.             $bSubscription $b->subscription 0;
  162.             // 昇順でソート(定期購入商品を後に)
  163.             return $aSubscription $bSubscription;
  164.         });
  165.         // ソート後の配列でpaginationオブジェクトを更新
  166.         $pagination->setItems($products);
  167.         $ids = [];
  168.         foreach ($pagination as $Product) {
  169.             $ids[] = $Product->getId();
  170.         }
  171.         $ProductsAndClassCategories $this->productRepository->findProductsWithSortedClassCategories($ids'p.id');
  172.         // addCart form
  173.         $forms = [];
  174.         foreach ($pagination as $Product) {
  175.             /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  176.             $builder $this->formFactory->createNamedBuilder(
  177.                 '',
  178.                 AddCartType::class,
  179.                 null,
  180.                 [
  181.                     'product' => $ProductsAndClassCategories[$Product->getId()],
  182.                     'allow_extra_fields' => true,
  183.                 ]
  184.             );
  185.             $addCartForm $builder->getForm();
  186.             $forms[$Product->getId()] = $addCartForm->createView();
  187.         }
  188.         $Category $searchForm->get('category_id')->getData();
  189.         $subMapRaw getenv('SUBSCRIPTION_MAP');
  190.         $subMap = [];
  191.         if (!empty($subMapRaw)) {
  192.             $subMapRaw explode(','$subMapRaw);
  193.             foreach ($subMapRaw as $map) {
  194.                 $map explode(':'$map);
  195.                 $subMap[$map[0]] = $map[1];
  196.             }
  197.         }
  198.         return [
  199.             'subtitle' => $this->getPageTitle($searchData),
  200.             'pagination' => $pagination,
  201.             'search_form' => $searchForm->createView(),
  202.             'forms' => $forms,
  203.             'Category' => $Category,
  204.             'subMap' => $subMap,
  205.         ];
  206.     }
  207.     /**
  208.      * 商品詳細画面.
  209.      *
  210.      * @Route("/products/detail/{id}", name="product_detail", methods={"GET"}, requirements={"id" = "\d+"})
  211.      * @Template("Product/detail.twig")
  212.      * @ParamConverter("Product", options={"repository_method" = "findWithSortedClassCategories"})
  213.      *
  214.      * @param Request $request
  215.      * @param Product $Product
  216.      *
  217.      * @return array
  218.      */
  219.     public function detail(Request $requestProduct $Product)
  220.     {
  221.         if (!$this->checkVisibility($Product)) {
  222.             throw new NotFoundHttpException();
  223.         }
  224.         $builder $this->formFactory->createNamedBuilder(
  225.             '',
  226.             AddCartType::class,
  227.             null,
  228.             [
  229.                 'product' => $Product,
  230.                 'id_add_product_id' => false,
  231.             ]
  232.         );
  233.         $event = new EventArgs(
  234.             [
  235.                 'builder' => $builder,
  236.                 'Product' => $Product,
  237.             ],
  238.             $request
  239.         );
  240.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE);
  241.         $is_favorite false;
  242.         if ($this->isGranted('ROLE_USER')) {
  243.             $Customer $this->getUser();
  244.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  245.         }
  246.         $sale_type_id $Product->getProductClasses()[0]->getSaleType()->getId();
  247.         $delivery $this->entityManager->getRepository(Delivery::class)->getDeliveries($sale_type_id);
  248.         $fees $delivery[0]->getDeliveryFees()->map(function ($fee) {
  249.             return $fee->getFee();
  250.         })->toArray();
  251.         $fee min($fees);
  252.         return [
  253.             'title' => $this->title,
  254.             'subtitle' => $Product->getName(),
  255.             'form' => $builder->getForm()->createView(),
  256.             'Product' => $Product,
  257.             'is_favorite' => $is_favorite,
  258.             'fee' => $fee,
  259.         ];
  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.             // is_hiddenフラグがtrueの商品は表示しない
  446.             if ($Product->isHidden()) {
  447.                 return false;
  448.             }
  449.         }
  450.         return true;
  451.     }
  452. }