app/Customize/Controller/ProductController.php line 311

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\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\Paginator;
  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. use Eccube\Controller\AbstractController;
  39. use Eccube\Controller\ProductController as OriginalProductController;
  40. class ProductController extends OriginalProductController
  41. {
  42.         /**
  43.      * @var PurchaseFlow
  44.      */
  45.     protected $purchaseFlow;
  46.     /**
  47.      * @var CustomerFavoriteProductRepository
  48.      */
  49.     protected $customerFavoriteProductRepository;
  50.     /**
  51.      * @var CartService
  52.      */
  53.     protected $cartService;
  54.     /**
  55.      * @var ProductRepository
  56.      */
  57.     protected $productRepository;
  58.     /**
  59.      * @var BaseInfo
  60.      */
  61.     protected $BaseInfo;
  62.     /**
  63.      * @var AuthenticationUtils
  64.      */
  65.     protected $helper;
  66.     /**
  67.      * @var ProductListMaxRepository
  68.      */
  69.     protected $productListMaxRepository;
  70.     private $title '';
  71.     /**
  72.      * ProductController constructor.
  73.      *
  74.      * @param PurchaseFlow $cartPurchaseFlow
  75.      * @param CustomerFavoriteProductRepository $customerFavoriteProductRepository
  76.      * @param CartService $cartService
  77.      * @param ProductRepository $productRepository
  78.      * @param BaseInfoRepository $baseInfoRepository
  79.      * @param AuthenticationUtils $helper
  80.      * @param ProductListMaxRepository $productListMaxRepository
  81.      */
  82.     public function __construct(
  83.         PurchaseFlow $cartPurchaseFlow,
  84.         CustomerFavoriteProductRepository $customerFavoriteProductRepository,
  85.         CartService $cartService,
  86.         ProductRepository $productRepository,
  87.         BaseInfoRepository $baseInfoRepository,
  88.         AuthenticationUtils $helper,
  89.         ProductListMaxRepository $productListMaxRepository
  90.     ) {
  91.         $this->purchaseFlow $cartPurchaseFlow;
  92.         $this->customerFavoriteProductRepository $customerFavoriteProductRepository;
  93.         $this->cartService $cartService;
  94.         $this->productRepository $productRepository;
  95.         $this->BaseInfo $baseInfoRepository->get();
  96.         $this->helper $helper;
  97.         $this->productListMaxRepository $productListMaxRepository;
  98.     }
  99.     /**
  100.      * 商品一覧画面.
  101.      *
  102.      * @Route("/products/list", name="product_list")
  103.      * @Template("Product/list.twig")
  104.      */
  105.     public function index(Request $requestPaginator $paginator)
  106.     {
  107.         // Doctrine SQLFilter
  108.         if ($this->BaseInfo->isOptionNostockHidden()) {
  109.             $this->entityManager->getFilters()->enable('option_nostock_hidden');
  110.         }
  111.         // handleRequestは空のqueryの場合は無視するため
  112.         if ($request->getMethod() === 'GET') {
  113.             $request->query->set('pageno'$request->query->get('pageno'''));
  114.         }
  115.         // searchForm
  116.         /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  117.         $builder $this->formFactory->createNamedBuilder(''SearchProductType::class);
  118.         if ($request->getMethod() === 'GET') {
  119.             $builder->setMethod('GET');
  120.         }
  121.         $event = new EventArgs(
  122.             [
  123.                 'builder' => $builder,
  124.             ],
  125.             $request
  126.         );
  127.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_INDEX_INITIALIZE$event);
  128.         /* @var $searchForm \Symfony\Component\Form\FormInterface */
  129.         $searchForm $builder->getForm();
  130.         $searchForm->handleRequest($request);
  131.         // paginator
  132.         $searchData $searchForm->getData();
  133.         $qb $this->productRepository->getQueryBuilderBySearchData($searchData);
  134.         $event = new EventArgs(
  135.             [
  136.                 'searchData' => $searchData,
  137.                 'qb' => $qb,
  138.             ],
  139.             $request
  140.         );
  141.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_INDEX_SEARCH$event);
  142.         $searchData $event->getArgument('searchData');
  143.         $query $qb->getQuery()
  144.             ->useResultCache(true$this->eccubeConfig['eccube_result_cache_lifetime_short']);
  145.         /** @var SlidingPagination $pagination */
  146.         $pagination $paginator->paginate(
  147.             $query,
  148.             !empty($searchData['pageno']) ? $searchData['pageno'] : 1,
  149.             !empty($searchData['disp_number']) ? $searchData['disp_number']->getId() : $this->productListMaxRepository->findOneBy([], ['sort_no' => 'ASC'])->getId()
  150.         );
  151.         $ids = [];
  152.         foreach ($pagination as $Product) {
  153.             $ids[] = $Product->getId();
  154.         }
  155.         $ProductsAndClassCategories $this->productRepository->findProductsWithSortedClassCategories($ids'p.id');
  156.         // addCart form
  157.         $forms = [];
  158.         foreach ($pagination as $Product) {
  159.             /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  160.             $builder $this->formFactory->createNamedBuilder(
  161.                 '',
  162.                 AddCartType::class,
  163.                 null,
  164.                 [
  165.                     'product' => $ProductsAndClassCategories[$Product->getId()],
  166.                     'allow_extra_fields' => true,
  167.                 ]
  168.             );
  169.             $addCartForm $builder->getForm();
  170.             $forms[$Product->getId()] = $addCartForm->createView();
  171.         }
  172.         // 表示件数
  173.         $builder $this->formFactory->createNamedBuilder(
  174.             'disp_number',
  175.             ProductListMaxType::class,
  176.             null,
  177.             [
  178.                 'required' => false,
  179.                 'allow_extra_fields' => true,
  180.             ]
  181.         );
  182.         if ($request->getMethod() === 'GET') {
  183.             $builder->setMethod('GET');
  184.         }
  185.         $event = new EventArgs(
  186.             [
  187.                 'builder' => $builder,
  188.             ],
  189.             $request
  190.         );
  191.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_INDEX_DISP$event);
  192.         $dispNumberForm $builder->getForm();
  193.         $dispNumberForm->handleRequest($request);
  194.         // ソート順
  195.         $builder $this->formFactory->createNamedBuilder(
  196.             'orderby',
  197.             ProductListOrderByType::class,
  198.             null,
  199.             [
  200.                 'required' => false,
  201.                 'allow_extra_fields' => true,
  202.             ]
  203.         );
  204.         if ($request->getMethod() === 'GET') {
  205.             $builder->setMethod('GET');
  206.         }
  207.         $event = new EventArgs(
  208.             [
  209.                 'builder' => $builder,
  210.             ],
  211.             $request
  212.         );
  213.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_INDEX_ORDER$event);
  214.         $orderByForm $builder->getForm();
  215.         $orderByForm->handleRequest($request);
  216.         $Category $searchForm->get('category_id')->getData();
  217.         /*
  218.          *mv画像のパスの設定
  219.          */
  220.         $mv_path_pc "";
  221.         $mv_path_sp "";
  222.         if(!empty($_GET['category_id'])){
  223.             $mv_path_pc "/html/user_data/assets/img/category/mv_category_".$_GET['category_id'].".png";
  224.             $mv_path_sp "/html/user_data/assets/img/category/mv_category_".$_GET['category_id']."_sp.png";
  225.             //ファイルがある場合は対応する命名規則のファイルない場合はempty
  226.             if(!file_exists($_SERVER['DOCUMENT_ROOT'].$mv_path_pc)) $mv_path_pc "";
  227.             if(!file_exists($_SERVER['DOCUMENT_ROOT'].$mv_path_sp)) $mv_path_sp "";
  228.         }
  229.         if( $mv_path_pc == '' ){
  230.             $mv_path_pc "/html/user_data/assets/img/category/mv_category_default.png";
  231.         }
  232.         if( $mv_path_sp == '' ){
  233.             $mv_path_sp "/html/user_data/assets/img/category/mv_category_default_sp.png";
  234.         }
  235.         $seo_description "";
  236.         if($Category && $Category->getSeoDescription()){
  237.             $seo_description $Category->getSeoDescription();
  238.         }
  239.         $seo_keyword "";
  240.         if($Category && $Category->getSeoKeyword()){
  241.             $seo_keyword $Category->getSeoKeyword();
  242.         }
  243.         return [
  244.             'subtitle' => $this->getPageTitle($searchData),
  245.             'pagination' => $pagination,
  246.             'search_form' => $searchForm->createView(),
  247.             'disp_number_form' => $dispNumberForm->createView(),
  248.             'order_by_form' => $orderByForm->createView(),
  249.             'forms' => $forms,
  250.             'Category' => $Category,
  251.             'mv_path_pc' => $mv_path_pc,
  252.             'mv_path_sp' => $mv_path_sp,
  253.             'seo_description' => $seo_description,
  254.             'seo_keyword' => $seo_keyword,
  255.         ];
  256.     }
  257.     /**
  258.      * 商品詳細画面.
  259.      *
  260.      * @Route("/products/detail/{id}", name="product_detail", methods={"GET"}, requirements={"id" = "\d+"})
  261.      * @Template("Product/detail.twig")
  262.      * @ParamConverter("Product", options={"repository_method" = "findWithSortedClassCategories"})
  263.      *
  264.      * @param Request $request
  265.      * @param Product $Product
  266.      *
  267.      * @return array
  268.      */
  269.     public function detail(Request $requestProduct $Product)
  270.     {
  271.         if (!$this->checkVisibility($Product)) {
  272.             throw new NotFoundHttpException();
  273.         }
  274.         $builder $this->formFactory->createNamedBuilder(
  275.             '',
  276.             AddCartType::class,
  277.             null,
  278.             [
  279.                 'product' => $Product,
  280.                 'id_add_product_id' => false,
  281.             ]
  282.         );
  283.         $event = new EventArgs(
  284.             [
  285.                 'builder' => $builder,
  286.                 'Product' => $Product,
  287.             ],
  288.             $request
  289.         );
  290.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE$event);
  291.         $is_favorite false;
  292.         if ($this->isGranted('ROLE_USER')) {
  293.             $Customer $this->getUser();
  294.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  295.         }
  296.         //SEO設定
  297.         $seo_title $Product->getName();
  298.         if($Product->getSeoTitle()){
  299.             $seo_title $Product->getSeoTitle();
  300.         }
  301.         $seo_description $Product->getName()." | ".mb_substr(str_replace("\n","",$Product->getDescriptionDetail()),0,150);
  302.         if($Product->getSeoDescription()){
  303.             $seo_description $Product->getSeoDescription();
  304.         }
  305.         $seo_keyword '';
  306.         if($Product->getSeoKeyword()){
  307.             $seo_keyword $Product->getSeoKeyword();
  308.         }
  309.         
  310.         return [
  311.             'title' => $this->title,
  312.             // 'subtitle' => $Product->getName(),
  313.             'form' => $builder->getForm()->createView(),
  314.             'form1' => $builder->getForm()->createView(),
  315.             'Product' => $Product,
  316.             'is_favorite' => $is_favorite,
  317.             'subtitle' => $seo_title,
  318.             'seo_description' => $seo_description,
  319.             'seo_keyword' => $seo_keyword
  320.         ];
  321.     }
  322.     /**
  323.      * カートに追加.
  324.      *
  325.      * @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
  326.      */
  327.     public function addCart(Request $requestProduct $Product)
  328.     {
  329.         // エラーメッセージの配列
  330.         $errorMessages = [];
  331.         if (!$this->checkVisibility($Product)) {
  332.             throw new NotFoundHttpException();
  333.         }
  334.         $builder $this->formFactory->createNamedBuilder(
  335.             '',
  336.             AddCartType::class,
  337.             null,
  338.             [
  339.                 'product' => $Product,
  340.                 'id_add_product_id' => false,
  341.             ]
  342.         );
  343.         $event = new EventArgs(
  344.             [
  345.                 'builder' => $builder,
  346.                 'Product' => $Product,
  347.             ],
  348.             $request
  349.         );
  350.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE$event);
  351.         /* @var $form \Symfony\Component\Form\FormInterface */
  352.         $form $builder->getForm();
  353.         $form->handleRequest($request);
  354.         // print_r($request);
  355.         if (!$form->isValid()) {
  356.             throw new NotFoundHttpException();
  357.         }
  358.         $addCartData $form->getData();
  359.         log_info(
  360.             'カート追加処理開始',
  361.             [
  362.                 'product_id' => $Product->getId(),
  363.                 'product_class_id' => $addCartData['product_class_id'],
  364.                 'quantity' => $addCartData['quantity'],
  365.             ]
  366.         );
  367.         // カートへ追加
  368.         $this->cartService->addProduct($addCartData['product_class_id'], $addCartData['quantity']);
  369.         // 明細の正規化
  370.         $Carts $this->cartService->getCarts();
  371.         foreach ($Carts as $Cart) {
  372.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  373.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  374.             if ($result->hasError()) {
  375.                 $this->cartService->removeProduct($addCartData['product_class_id']);
  376.                 foreach ($result->getErrors() as $error) {
  377.                     $errorMessages[] = $error->getMessage();
  378.                 }
  379.             }
  380.             foreach ($result->getWarning() as $warning) {
  381.                 $errorMessages[] = $warning->getMessage();
  382.             }
  383.         }
  384.         $this->cartService->save();
  385.         log_info(
  386.             'カート追加処理完了',
  387.             [
  388.                 'product_id' => $Product->getId(),
  389.                 'product_class_id' => $addCartData['product_class_id'],
  390.                 'quantity' => $addCartData['quantity'],
  391.             ]
  392.         );
  393.         $event = new EventArgs(
  394.             [
  395.                 'form' => $form,
  396.                 'Product' => $Product,
  397.             ],
  398.             $request
  399.         );
  400.         $this->eventDispatcher->dispatch(EccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE$event);
  401.         if ($event->getResponse() !== null) {
  402.             return $event->getResponse();
  403.         }
  404.         if ($request->isXmlHttpRequest()) {
  405.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  406.             // 初期化
  407.             $done null;
  408.             $messages = [];
  409.             if (empty($errorMessages)) {
  410.                 // エラーが発生していない場合
  411.                 $done true;
  412.                 array_push($messagestrans('front.product.add_cart_complete'));
  413.             } else {
  414.                 // エラーが発生している場合
  415.                 $done false;
  416.                 $messages $errorMessages;
  417.             }
  418.             return $this->json(['done' => $done'messages' => $messages]);
  419.         } else {
  420.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  421.             foreach ($errorMessages as $errorMessage) {
  422.                 $this->addRequestError($errorMessage);
  423.             }
  424.             return $this->redirectToRoute('cart');
  425.         }
  426.     }
  427.     /**
  428.      * ページタイトルの設定
  429.      *
  430.      * @param  null|array $searchData
  431.      *
  432.      * @return str
  433.      */
  434.     protected function getPageTitle($searchData)
  435.     {
  436.         if (isset($searchData['name']) && !empty($searchData['name'])) {
  437.             return trans('front.product.search_result');
  438.         } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
  439.             if($searchData['category_id']->getSeoTitle()){
  440.                 return $searchData['category_id']->getSeoTitle();
  441.             }
  442.             return $searchData['category_id']->getName();
  443.         } else {
  444.             return trans('front.product.all_products');
  445.         }
  446.     }
  447. }