app/Customize/Controller/ProductController.php line 317

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\Entity\BaseInfo;
  14. use Eccube\Entity\Master\ProductStatus;
  15. use Eccube\Entity\Product;
  16. use Eccube\Entity\ProductClass;
  17. use Eccube\Event\EccubeEvents;
  18. use Eccube\Event\EventArgs;
  19. use Eccube\Form\Type\AddCartType;
  20. use Eccube\Form\Type\Master\ProductListMaxType;
  21. use Eccube\Form\Type\Master\ProductListOrderByType;
  22. use Eccube\Form\Type\SearchProductType;
  23. use Eccube\Repository\BaseInfoRepository;
  24. use Eccube\Repository\CustomerFavoriteProductRepository;
  25. use Plugin\RelatedProduct4\Repository\RelatedProductRepository;
  26. use Plugin\RelatedProduct4\Entity\RelatedProduct;
  27. use Eccube\Repository\Master\ProductListMaxRepository;
  28. use Customize\Repository\ProductRepository;
  29. use Customize\Repository\CatalogFaqRepository;
  30. use Customize\Repository\FaqRepository;
  31. use Eccube\Service\CartService;
  32. use Eccube\Service\PurchaseFlow\PurchaseContext;
  33. use Eccube\Service\PurchaseFlow\PurchaseFlow;
  34. use Knp\Bundle\PaginatorBundle\Pagination\SlidingPagination;
  35. use Knp\Component\Pager\Paginator;
  36. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  37. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  38. use Symfony\Component\HttpFoundation\Request;
  39. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  40. use Symfony\Component\Routing\Annotation\Route;
  41. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  42. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  43. use Eccube\Controller\AbstractController;
  44. class ProductController extends AbstractController
  45. {
  46.     /**
  47.      * @var PurchaseFlow
  48.      */
  49.     protected $purchaseFlow;
  50.     /**
  51.      * @var CustomerFavoriteProductRepository
  52.      */
  53.     protected $customerFavoriteProductRepository;
  54.     /**
  55.      * @var CartService
  56.      */
  57.     protected $cartService;
  58.     /**
  59.      * @var ProductRepository
  60.      */
  61.     protected $productRepository;
  62.     /**
  63.      * @var BaseInfo
  64.      */
  65.     protected $BaseInfo;
  66.     /**
  67.      * @var AuthenticationUtils
  68.      */
  69.     protected $helper;
  70.     /**
  71.      * @var ProductListMaxRepository
  72.      */
  73.     protected $productListMaxRepository;
  74.     /**
  75.      * @var CatalogFaqRepository
  76.      */
  77.     protected $catalogFaqRepository;
  78.     /**
  79.      * @var FaqRepository
  80.      */
  81.     protected $faqRepository;
  82.     private $title '';
  83.     /**
  84.      * @var RelatedProductRepository
  85.      */
  86.     protected $relatedProductRepository;
  87.     /**
  88.      * ProductController constructor.
  89.      *
  90.      * @param PurchaseFlow $cartPurchaseFlow
  91.      * @param CustomerFavoriteProductRepository $customerFavoriteProductRepository
  92.      * @param CartService $cartService
  93.      * @param ProductRepository $productRepository
  94.      * @param BaseInfoRepository $baseInfoRepository
  95.      * @param AuthenticationUtils $helper
  96.      * @param ProductListMaxRepository $productListMaxRepository
  97.      * @param RelatedProductRepository $relatedProductRepository
  98.      * @param CatalogFaqRepository $catalogFaqRepository
  99.      * @param FaqRepository $faqRepository
  100.      */
  101.     public function __construct(
  102.         PurchaseFlow $cartPurchaseFlow,
  103.         CustomerFavoriteProductRepository $customerFavoriteProductRepository,
  104.         CartService $cartService,
  105.         ProductRepository $productRepository,
  106.         BaseInfoRepository $baseInfoRepository,
  107.         AuthenticationUtils $helper,
  108.         ProductListMaxRepository $productListMaxRepository,
  109.         RelatedProductRepository $relatedProductRepository,
  110.         CatalogFaqRepository $catalogFaqRepository,
  111.         FaqRepository $faqRepository
  112.     ) {
  113.         $this->purchaseFlow $cartPurchaseFlow;
  114.         $this->customerFavoriteProductRepository $customerFavoriteProductRepository;
  115.         $this->cartService $cartService;
  116.         $this->productRepository $productRepository;
  117.         $this->BaseInfo $baseInfoRepository->get();
  118.         $this->helper $helper;
  119.         $this->productListMaxRepository $productListMaxRepository;
  120.         $this->relatedProductRepository $relatedProductRepository;
  121.         $this->catalogFaqRepository $catalogFaqRepository;
  122.         $this->faqRepository $faqRepository;
  123.     }
  124.     /**
  125.      * 商品一覧画面.
  126.      *
  127.      * @Route("/products/list", name="product_list")
  128.      * @Template("Product/list.twig")
  129.      */
  130.     public function index(Request $requestPaginator $paginator)
  131.     {
  132.         // Doctrine SQLFilter
  133.         if ($this->BaseInfo->isOptionNostockHidden()) {
  134.             $this->entityManager->getFilters()->enable('option_nostock_hidden');
  135.         }
  136.         // handleRequestは空のqueryの場合は無視するため
  137.         if ($request->getMethod() === 'GET') {
  138.             $request->query->set('pageno'$request->query->get('pageno'''));
  139.         }
  140.         // searchForm
  141.         /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  142.         $builder $this->formFactory->createNamedBuilder(''SearchProductType::class);
  143.         if ($request->getMethod() === 'GET') {
  144.             $builder->setMethod('GET');
  145.         }
  146.         $event = new EventArgs(
  147.             [
  148.                 'builder' => $builder,
  149.             ],
  150.             $request
  151.         );
  152.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_INDEX_INITIALIZE$event);
  153.         /* @var $searchForm \Symfony\Component\Form\FormInterface */
  154.         $searchForm $builder->getForm();
  155.         $searchForm->handleRequest($request);
  156.         // paginator
  157.         $searchData $searchForm->getData();
  158.         $qb $this->productRepository->getQueryBuilderBySearchData($searchData);
  159.         $event = new EventArgs(
  160.             [
  161.                 'searchData' => $searchData,
  162.                 'qb' => $qb,
  163.             ],
  164.             $request
  165.         );
  166.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_INDEX_SEARCH$event);
  167.         $searchData $event->getArgument('searchData');
  168.         $query $qb->getQuery()
  169.             ->useResultCache(true$this->eccubeConfig['eccube_result_cache_lifetime_short']);
  170.         /** @var SlidingPagination $pagination */
  171.         $pagination $paginator->paginate(
  172.             $query,
  173.             !empty($searchData['pageno']) ? $searchData['pageno'] : 1,
  174.             !empty($searchData['disp_number']) ? $searchData['disp_number']->getId() : $this->productListMaxRepository->findOneBy([], ['sort_no' => 'ASC'])->getId()
  175.         );
  176.         $ids = [];
  177.         $Categories = [];
  178.         $arrRelatedProducts = [];
  179.         foreach ($pagination as $Product) {
  180.             if ($Product->getRelatedProductsOnly() != 1) {
  181.                 foreach ($Product->getProductCategories() as $ProductCategory) {
  182.                     if ($ProductCategory->getCategory()->getId() != '19') { // レンタルサービス商品以外
  183.                         $RelatedProduct $this->relatedProductRepository->findBy([
  184.                             'Product' => $Product,
  185.                         ]);
  186.                         $Categories[$ProductCategory->getCategory()->getId()]['Category'] = $ProductCategory->getCategory();
  187.                         $Categories[$ProductCategory->getCategory()->getId()]['Products'][] = $Product;
  188.                         // $Categories[$ProductCategory->getCategory()->getId()]['RelatedProducts'] = [];
  189.                         foreach($RelatedProduct as $rp) {
  190.                             $arrRelatedProducts[$ProductCategory->getCategory()->getId()][$rp->getChildProduct()->getId()] = $rp->getChildProduct()->getId();
  191.                         }
  192.                     }
  193.                 }
  194.                 $ids[] = $Product->getId();
  195.             }
  196.         }
  197.         foreach($arrRelatedProducts as $key => $value) {
  198.             arsort($value);
  199.             $listRelatedProduct array_slice($value010);
  200.             $dataProduct $this->productRepository->getProductIntroductionList($listRelatedProduct);
  201.             foreach($dataProduct as $product) {
  202.                 if ($product->getStatus()->getId() == 1) {
  203.                     $Categories[$key]['RelatedProducts'][] = $product;
  204.                 }
  205.             }
  206.         }
  207.         // addCart form
  208.         $forms = [];
  209.         // 表示件数
  210.         $builder $this->formFactory->createNamedBuilder(
  211.             'disp_number',
  212.             ProductListMaxType::class,
  213.             null,
  214.             [
  215.                 'required' => false,
  216.                 'allow_extra_fields' => true,
  217.             ]
  218.         );
  219.         if ($request->getMethod() === 'GET') {
  220.             $builder->setMethod('GET');
  221.         }
  222.         $event = new EventArgs(
  223.             [
  224.                 'builder' => $builder,
  225.             ],
  226.             $request
  227.         );
  228.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_INDEX_DISP$event);
  229.         $dispNumberForm $builder->getForm();
  230.         $dispNumberForm->handleRequest($request);
  231.         // ソート順
  232.         $builder $this->formFactory->createNamedBuilder(
  233.             'orderby',
  234.             ProductListOrderByType::class,
  235.             null,
  236.             [
  237.                 'required' => false,
  238.                 'allow_extra_fields' => true,
  239.             ]
  240.         );
  241.         if ($request->getMethod() === 'GET') {
  242.             $builder->setMethod('GET');
  243.         }
  244.         $event = new EventArgs(
  245.             [
  246.                 'builder' => $builder,
  247.             ],
  248.             $request
  249.         );
  250.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_INDEX_ORDER$event);
  251.         $orderByForm $builder->getForm();
  252.         $orderByForm->handleRequest($request);
  253.         $Category $searchForm->get('category_id')->getData();
  254.         return [
  255.             'subtitle' => $this->getPageTitle($searchData),
  256.             'pagination' => $pagination,
  257.             'search_form' => $searchForm->createView(),
  258.             'disp_number_form' => $dispNumberForm->createView(),
  259.             'order_by_form' => $orderByForm->createView(),
  260.             'forms' => $forms,
  261.             'Category' => $Category,
  262.             'Categories' => $Categories
  263.         ];
  264.     }
  265.     /**
  266.      * 商品詳細画面.
  267.      *
  268.      * @Route("/products/detail/{id}", name="product_detail", methods={"GET"}, requirements={"id" = "\d+"})
  269.      * @Template("Product/detail.twig")
  270.      *
  271.      * @param Request $request
  272.      * @param integer $id
  273.      *
  274.      * @return array
  275.      */
  276.     public function detail(Request $request$id)
  277.     {
  278.         $Product $this->productRepository->findWithSortedClassCategories($id);
  279.         if (!$this->checkVisibility($Product)) {
  280.             throw new NotFoundHttpException();
  281.         }
  282.         $builder $this->formFactory->createNamedBuilder(
  283.             '',
  284.             AddCartType::class,
  285.             null,
  286.             [
  287.                 'product' => $Product,
  288.                 'id_add_product_id' => false,
  289.             ]
  290.         );
  291.         $event = new EventArgs(
  292.             [
  293.                 'builder' => $builder,
  294.                 'Product' => $Product,
  295.             ],
  296.             $request
  297.         );
  298.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE$event);
  299.         $is_favorite false;
  300.         if ($this->isGranted('ROLE_USER')) {
  301.             $Customer $this->getUser();
  302.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  303.         }
  304.         //product_url_video
  305.         $urlVideo $Product->getProductUrlVideo();
  306.         $youtube_id null;
  307.         if($urlVideo){
  308.             preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i'$urlVideo$match);
  309.             $youtube_id $match[1];
  310.         }
  311.         $first_image_pc "";
  312.         $first_image_mb "";
  313.         foreach ($Product->getProductImage() as $key => $image) {
  314.             if ($first_image_pc && $first_image_mb) {
  315.                 break;
  316.             }
  317.             $first_image_pc = !$first_image_pc && $image->getFilename() ? $image->getFilename() : $first_image_pc;
  318.             $first_image_mb = !$first_image_mb && $image->getImgMobile() ? $image->getImgMobile() : $first_image_mb;
  319.         }
  320.         $Product->image_pc $first_image_pc;
  321.         $Product->image_mb $first_image_mb;
  322.         
  323.         return [
  324.             'title' => $this->title,
  325.             'subtitle' => $Product->getName(),
  326.             'form' => $builder->getForm()->createView(),
  327.             'Product' => $Product,
  328.             'videoUrl' => $youtube_id 'https://www.youtube.com/embed/'.$youtube_id'',
  329.             'is_favorite' => $is_favorite,
  330.         ];
  331.     }
  332.     /**
  333.      * お気に入り追加.
  334.      *
  335.      * @Route("/products/add_favorite/{id}", name="product_add_favorite", requirements={"id" = "\d+"})
  336.      */
  337.     public function addFavorite(Request $requestProduct $Product)
  338.     {
  339.         $this->checkVisibility($Product);
  340.         $event = new EventArgs(
  341.             [
  342.                 'Product' => $Product,
  343.             ],
  344.             $request
  345.         );
  346.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_INITIALIZE$event);
  347.         if ($this->isGranted('ROLE_USER')) {
  348.             $Customer $this->getUser();
  349.             $this->customerFavoriteProductRepository->addFavorite($Customer$Product);
  350.             $this->session->getFlashBag()->set('product_detail.just_added_favorite'$Product->getId());
  351.             $event = new EventArgs(
  352.                 [
  353.                     'Product' => $Product,
  354.                 ],
  355.                 $request
  356.             );
  357.             $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE$event);
  358.             return $this->redirectToRoute('product_detail', ['id' => $Product->getId()]);
  359.         } else {
  360.             // 非会員の場合、ログイン画面を表示
  361.             //  ログイン後の画面遷移先を設定
  362.             $this->setLoginTargetPath($this->generateUrl('product_add_favorite', ['id' => $Product->getId()], UrlGeneratorInterface::ABSOLUTE_URL));
  363.             $this->session->getFlashBag()->set('eccube.add.favorite'true);
  364.             $event = new EventArgs(
  365.                 [
  366.                     'Product' => $Product,
  367.                 ],
  368.                 $request
  369.             );
  370.             $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE$event);
  371.             return $this->redirectToRoute('mypage_login');
  372.         }
  373.     }
  374.     /**
  375.      * カートに追加.
  376.      *
  377.      * @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
  378.      */
  379.     public function addCart(Request $requestProduct $Product)
  380.     {
  381.         // エラーメッセージの配列
  382.         $errorMessages = [];
  383.         if (!$this->checkVisibility($Product)) {
  384.             throw new NotFoundHttpException();
  385.         }
  386.         $builder $this->formFactory->createNamedBuilder(
  387.             '',
  388.             AddCartType::class,
  389.             null,
  390.             [
  391.                 'product' => $Product,
  392.                 'id_add_product_id' => false,
  393.             ]
  394.         );
  395.         $event = new EventArgs(
  396.             [
  397.                 'builder' => $builder,
  398.                 'Product' => $Product,
  399.             ],
  400.             $request
  401.         );
  402.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE$event);
  403.         /* @var $form \Symfony\Component\Form\FormInterface */
  404.         $form $builder->getForm();
  405.         $form->handleRequest($request);
  406.         if (!$form->isValid()) {
  407.             throw new NotFoundHttpException();
  408.         }
  409.         $addCartData $form->getData();
  410.         log_info(
  411.             'カート追加処理開始',
  412.             [
  413.                 'product_id' => $Product->getId(),
  414.                 'product_class_id' => $addCartData['product_class_id'],
  415.                 'quantity' => $addCartData['quantity'],
  416.             ]
  417.         );
  418.         // カートへ追加
  419.         $this->cartService->addProduct($addCartData['product_class_id'], $addCartData['quantity']);
  420.         // 明細の正規化
  421.         $Carts $this->cartService->getCarts();
  422.         foreach ($Carts as $Cart) {
  423.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  424.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  425.             if ($result->hasError()) {
  426.                 $this->cartService->removeProduct($addCartData['product_class_id']);
  427.                 foreach ($result->getErrors() as $error) {
  428.                     $errorMessages[] = $error->getMessage();
  429.                 }
  430.             }
  431.             foreach ($result->getWarning() as $warning) {
  432.                 $errorMessages[] = $warning->getMessage();
  433.             }
  434.         }
  435.         $this->cartService->save();
  436.         log_info(
  437.             'カート追加処理完了',
  438.             [
  439.                 'product_id' => $Product->getId(),
  440.                 'product_class_id' => $addCartData['product_class_id'],
  441.                 'quantity' => $addCartData['quantity'],
  442.             ]
  443.         );
  444.         $event = new EventArgs(
  445.             [
  446.                 'form' => $form,
  447.                 'Product' => $Product,
  448.             ],
  449.             $request
  450.         );
  451.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE$event);
  452.         if ($event->getResponse() !== null) {
  453.             return $event->getResponse();
  454.         }
  455.         if ($request->isXmlHttpRequest()) {
  456.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  457.             // 初期化
  458.             $done null;
  459.             $messages = [];
  460.             if (empty($errorMessages)) {
  461.                 // エラーが発生していない場合
  462.                 $done true;
  463.                 array_push($messagestrans('front.product.add_cart_complete'));
  464.             } else {
  465.                 // エラーが発生している場合
  466.                 $done false;
  467.                 $messages $errorMessages;
  468.             }
  469.             return $this->json(['done' => $done'messages' => $messages]);
  470.         } else {
  471.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  472.             foreach ($errorMessages as $errorMessage) {
  473.                 $this->addRequestError($errorMessage);
  474.             }
  475.             return $this->redirectToRoute('cart');
  476.         }
  477.     }
  478.     /**
  479.      * ページタイトルの設定
  480.      *
  481.      * @param  null|array $searchData
  482.      *
  483.      * @return str
  484.      */
  485.     protected function getPageTitle($searchData)
  486.     {
  487.         if (isset($searchData['name']) && !empty($searchData['name'])) {
  488.             return trans('front.product.search_result');
  489.         } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
  490.             return $searchData['category_id']->getName();
  491.         } else {
  492.             return trans('front.product.all_products');
  493.         }
  494.     }
  495.     /**
  496.      * 閲覧可能な商品かどうかを判定
  497.      *
  498.      * @param Product $Product
  499.      *
  500.      * @return boolean 閲覧可能な場合はtrue
  501.      */
  502.     protected function checkVisibility(Product $Product)
  503.     {
  504.         $is_admin $this->session->has('_security_admin');
  505.         // 管理ユーザの場合はステータスやオプションにかかわらず閲覧可能.
  506.         if (!$is_admin) {
  507.             // 在庫なし商品の非表示オプションが有効な場合.
  508.             // if ($this->BaseInfo->isOptionNostockHidden()) {
  509.             //     if (!$Product->getStockFind()) {
  510.             //         return false;
  511.             //     }
  512.             // }
  513.             // 公開ステータスでない商品は表示しない.
  514.             if ($Product->getStatus()->getId() !== ProductStatus::DISPLAY_SHOW) {
  515.                 return false;
  516.             }
  517.         }
  518.         return true;
  519.     }
  520. }