src/Eccube/Controller/ProductController.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 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\Master\ProductListMaxType;
  20. use Eccube\Form\Type\Master\ProductListOrderByType;
  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 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.     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(EccubeEvents::FRONT_PRODUCT_INDEX_INITIALIZE$event);
  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.         $event = new EventArgs(
  133.             [
  134.                 'searchData' => $searchData,
  135.                 'qb' => $qb,
  136.             ],
  137.             $request
  138.         );
  139.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_INDEX_SEARCH$event);
  140.         $searchData $event->getArgument('searchData');
  141.         $query $qb->getQuery()
  142.             ->useResultCache(true$this->eccubeConfig['eccube_result_cache_lifetime_short']);
  143.         /** @var SlidingPagination $pagination */
  144.         $pagination $paginator->paginate(
  145.             $query,
  146.             !empty($searchData['pageno']) ? $searchData['pageno'] : 1,
  147.             !empty($searchData['disp_number']) ? $searchData['disp_number']->getId() : $this->productListMaxRepository->findOneBy([], ['sort_no' => 'ASC'])->getId()
  148.         );
  149.         $ids = [];
  150.         foreach ($pagination as $Product) {
  151.             $ids[] = $Product->getId();
  152.         }
  153.         $ProductsAndClassCategories $this->productRepository->findProductsWithSortedClassCategories($ids'p.id');
  154.         // addCart form
  155.         $forms = [];
  156.         foreach ($pagination as $Product) {
  157.             /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  158.             $builder $this->formFactory->createNamedBuilder(
  159.                 '',
  160.                 AddCartType::class,
  161.                 null,
  162.                 [
  163.                     'product' => $ProductsAndClassCategories[$Product->getId()],
  164.                     'allow_extra_fields' => true,
  165.                 ]
  166.             );
  167.             $addCartForm $builder->getForm();
  168.             $forms[$Product->getId()] = $addCartForm->createView();
  169.         }
  170.         // 表示件数
  171.         $builder $this->formFactory->createNamedBuilder(
  172.             'disp_number',
  173.             ProductListMaxType::class,
  174.             null,
  175.             [
  176.                 'required' => false,
  177.                 'allow_extra_fields' => true,
  178.             ]
  179.         );
  180.         if ($request->getMethod() === 'GET') {
  181.             $builder->setMethod('GET');
  182.         }
  183.         $event = new EventArgs(
  184.             [
  185.                 'builder' => $builder,
  186.             ],
  187.             $request
  188.         );
  189.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_INDEX_DISP$event);
  190.         $dispNumberForm $builder->getForm();
  191.         $dispNumberForm->handleRequest($request);
  192.         // ソート順
  193.         $builder $this->formFactory->createNamedBuilder(
  194.             'orderby',
  195.             ProductListOrderByType::class,
  196.             null,
  197.             [
  198.                 'required' => false,
  199.                 'allow_extra_fields' => true,
  200.             ]
  201.         );
  202.         if ($request->getMethod() === 'GET') {
  203.             $builder->setMethod('GET');
  204.         }
  205.         $event = new EventArgs(
  206.             [
  207.                 'builder' => $builder,
  208.             ],
  209.             $request
  210.         );
  211.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_INDEX_ORDER$event);
  212.         $orderByForm $builder->getForm();
  213.         $orderByForm->handleRequest($request);
  214.         $Category $searchForm->get('category_id')->getData();
  215.         $conn $this->getDoctrine()->getManager();
  216.         $sql "SELECT dp.description_detail ,dp.id ,dp.name ,dp.size ,dpi.file_name ,dpc.price02 ,( dpc.price02 * 1.1 ) as price02Tax FROM dtb_product as dp 
  217.         inner join dtb_product_class as dpc on ( dp.id = dpc.product_id )
  218.         inner join dtb_product_image as dpi on ( dp.id = dpi.product_id )  where dp.product_status_id = 1 and dpi.sort_no = 1 and dpc.sale_type_id = 3
  219.         ";
  220.         $stmt $conn->getConnection()->prepare($sql);
  221.         $stmt->execute();
  222.         $termProducts $stmt->fetchAll();
  223.         $termProduct = array();
  224.         foreach ($termProducts as $product) {
  225.             $termProduct[$product["id"]] = $product;
  226.         }
  227.         return [
  228.             'subtitle' => $this->getPageTitle($searchData),
  229.             'pagination' => $pagination,
  230.             'search_form' => $searchForm->createView(),
  231.             'disp_number_form' => $dispNumberForm->createView(),
  232.             'order_by_form' => $orderByForm->createView(),
  233.             'forms' => $forms,
  234.             'Category' => $Category,
  235.             'termProduct' => $termProduct,
  236.         ];
  237.     }
  238.     /**
  239.      * 商品詳細画面.
  240.      *
  241.      * @Route("/products/detail/{id}", name="product_detail", methods={"GET"}, requirements={"id" = "\d+"})
  242.      * @Template("Product/detail.twig")
  243.      * @ParamConverter("Product", options={"repository_method" = "findWithSortedClassCategories"})
  244.      *
  245.      * @param Request $request
  246.      * @param Product $Product
  247.      *
  248.      * @return array
  249.      */
  250.     public function detail(Request $requestProduct $Product)
  251.     {
  252.         if (!$this->checkVisibility($Product)) {
  253.             throw new NotFoundHttpException();
  254.         }
  255.         $builder $this->formFactory->createNamedBuilder(
  256.             '',
  257.             AddCartType::class,
  258.             null,
  259.             [
  260.                 'product' => $Product,
  261.                 'id_add_product_id' => false,
  262.             ]
  263.         );
  264.         $event = new EventArgs(
  265.             [
  266.                 'builder' => $builder,
  267.                 'Product' => $Product,
  268.             ],
  269.             $request
  270.         );
  271.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE$event);
  272.         $is_favorite false;
  273.         if ($this->isGranted('ROLE_USER')) {
  274.             $Customer $this->getUser();
  275.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  276.         }
  277.         return [
  278.             'title' => $this->title,
  279.             'subtitle' => $Product->getName(),
  280.             'form' => $builder->getForm()->createView(),
  281.             'Product' => $Product,
  282.             'is_favorite' => $is_favorite,
  283.         ];
  284.     }
  285.     /**
  286.      * お気に入り追加.
  287.      *
  288.      * @Route("/products/add_favorite/{id}", name="product_add_favorite", requirements={"id" = "\d+"}, methods={"GET", "POST"})
  289.      */
  290.     public function addFavorite(Request $requestProduct $Product)
  291.     {
  292.         $this->checkVisibility($Product);
  293.         $event = new EventArgs(
  294.             [
  295.                 'Product' => $Product,
  296.             ],
  297.             $request
  298.         );
  299.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_INITIALIZE$event);
  300.         if ($this->isGranted('ROLE_USER')) {
  301.             $Customer $this->getUser();
  302.             $this->customerFavoriteProductRepository->addFavorite($Customer$Product);
  303.             $this->session->getFlashBag()->set('product_detail.just_added_favorite'$Product->getId());
  304.             $event = new EventArgs(
  305.                 [
  306.                     'Product' => $Product,
  307.                 ],
  308.                 $request
  309.             );
  310.             $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE$event);
  311.             return $this->redirectToRoute('product_detail', ['id' => $Product->getId()]);
  312.         } else {
  313.             // 非会員の場合、ログイン画面を表示
  314.             //  ログイン後の画面遷移先を設定
  315.             $this->setLoginTargetPath($this->generateUrl('product_add_favorite', ['id' => $Product->getId()], UrlGeneratorInterface::ABSOLUTE_URL));
  316.             $this->session->getFlashBag()->set('eccube.add.favorite'true);
  317.             $event = new EventArgs(
  318.                 [
  319.                     'Product' => $Product,
  320.                 ],
  321.                 $request
  322.             );
  323.             $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE$event);
  324.             return $this->redirectToRoute('mypage_login');
  325.         }
  326.     }
  327.     /**
  328.      * カートに追加.
  329.      *
  330.      * @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
  331.      */
  332.     public function addCart(Request $requestProduct $Product)
  333.     {
  334.         // エラーメッセージの配列
  335.         $errorMessages = [];
  336.         if (!$this->checkVisibility($Product)) {
  337.             throw new NotFoundHttpException();
  338.         }
  339.         $builder $this->formFactory->createNamedBuilder(
  340.             '',
  341.             AddCartType::class,
  342.             null,
  343.             [
  344.                 'product' => $Product,
  345.                 'id_add_product_id' => false,
  346.             ]
  347.         );
  348.         $event = new EventArgs(
  349.             [
  350.                 'builder' => $builder,
  351.                 'Product' => $Product,
  352.             ],
  353.             $request
  354.         );
  355.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE$event);
  356.         /* @var $form \Symfony\Component\Form\FormInterface */
  357.         $form $builder->getForm();
  358.         $form->handleRequest($request);
  359.         if (!$form->isValid()) {
  360.             throw new NotFoundHttpException();
  361.         }
  362.         $addCartData $form->getData();
  363.         log_info(
  364.             'カート追加処理開始',
  365.             [
  366.                 'product_id' => $Product->getId(),
  367.                 'product_class_id' => $addCartData['product_class_id'],
  368.                 'quantity' => $addCartData['quantity'],
  369.             ]
  370.         );
  371.         // カートへ追加
  372.         $this->cartService->addProduct($addCartData['product_class_id'], $addCartData['quantity']);
  373.         // 明細の正規化
  374.         $Carts $this->cartService->getCarts();
  375.         foreach ($Carts as $Cart) {
  376.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  377.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  378.             if ($result->hasError()) {
  379.                 $this->cartService->removeProduct($addCartData['product_class_id']);
  380.                 foreach ($result->getErrors() as $error) {
  381.                     $errorMessages[] = $error->getMessage();
  382.                 }
  383.             }
  384.             foreach ($result->getWarning() as $warning) {
  385.                 $errorMessages[] = $warning->getMessage();
  386.             }
  387.         }
  388.         $this->cartService->save();
  389.         log_info(
  390.             'カート追加処理完了',
  391.             [
  392.                 'product_id' => $Product->getId(),
  393.                 'product_class_id' => $addCartData['product_class_id'],
  394.                 'quantity' => $addCartData['quantity'],
  395.             ]
  396.         );
  397.         $event = new EventArgs(
  398.             [
  399.                 'form' => $form,
  400.                 'Product' => $Product,
  401.             ],
  402.             $request
  403.         );
  404.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE$event);
  405.         if ($event->getResponse() !== null) {
  406.             return $event->getResponse();
  407.         }
  408.         if ($request->isXmlHttpRequest()) {
  409.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  410.             // 初期化
  411.             $done null;
  412.             $messages = [];
  413.             if (empty($errorMessages)) {
  414.                 // エラーが発生していない場合
  415.                 $done true;
  416.                 array_push($messagestrans('front.product.add_cart_complete'));
  417.             } else {
  418.                 // エラーが発生している場合
  419.                 $done false;
  420.                 $messages $errorMessages;
  421.             }
  422.             return $this->json(['done' => $done'messages' => $messages]);
  423.         } else {
  424.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  425.             foreach ($errorMessages as $errorMessage) {
  426.                 $this->addRequestError($errorMessage);
  427.             }
  428.             return $this->redirectToRoute('cart');
  429.         }
  430.     }
  431.     /**
  432.      * ページタイトルの設定
  433.      *
  434.      * @param  array|null $searchData
  435.      *
  436.      * @return str
  437.      */
  438.     protected function getPageTitle($searchData)
  439.     {
  440.         if (isset($searchData['name']) && !empty($searchData['name'])) {
  441.             return trans('front.product.search_result');
  442.         } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
  443.             return $searchData['category_id']->getName();
  444.         } else {
  445.             return trans('front.product.all_products');
  446.         }
  447.     }
  448.     /**
  449.      * 閲覧可能な商品かどうかを判定
  450.      *
  451.      * @param Product $Product
  452.      *
  453.      * @return boolean 閲覧可能な場合はtrue
  454.      */
  455.     protected function checkVisibility(Product $Product)
  456.     {
  457.         $is_admin $this->session->has('_security_admin');
  458.         // 管理ユーザの場合はステータスやオプションにかかわらず閲覧可能.
  459.         if (!$is_admin) {
  460.             // 在庫なし商品の非表示オプションが有効な場合.
  461.             // if ($this->BaseInfo->isOptionNostockHidden()) {
  462.             //     if (!$Product->getStockFind()) {
  463.             //         return false;
  464.             //     }
  465.             // }
  466.             // 公開ステータスでない商品は表示しない.
  467.             if ($Product->getStatus()->getId() !== ProductStatus::DISPLAY_SHOW) {
  468.                 return false;
  469.             }
  470.         }
  471.         return true;
  472.     }
  473. }