src/Eccube/Controller/ProductController.php line 114

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