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.         $builder $this->formFactory->createNamedBuilder(
  195.             '',
  196.             AddCartType::class,
  197.             null,
  198.             [
  199.                 'product' => $Product,
  200.                 'id_add_product_id' => false,
  201.                 
  202.             ]
  203.         );
  204.         
  205.         $event = new EventArgs(
  206.             [
  207.                 'builder' => $builder,
  208.                 'Product' => $Product,
  209.             ],
  210.             $request
  211.         );
  212.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE);
  213.         $is_favorite false;
  214.         if ($this->isGranted('ROLE_USER')) {
  215.             $Customer $this->getUser();
  216.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  217.         }
  218.         /* foreach($Product->getProductAccessPermissionSchools() as $value){
  219.             dump($value['productclass']);
  220.         }
  221.         */
  222.         
  223.         //カテゴリ2の表示項目を作成(カテゴリ1選択後の表示用) array[category1_id=>[category2_id=>category2_name]]
  224.         $categories2 $this->setDetailCategory2($Product);
  225.         return [    
  226.             'title' => $this->title,
  227.             'subtitle' => $Product->getName(),
  228.             'school_id' => $this->getUser()->getSchoolId(),
  229.             'categories2_array' => $categories2,
  230.             'form' => $builder->getForm()->createView(),
  231.             'Product' => $Product,
  232.             'is_favorite' => $is_favorite,
  233.         ];
  234.     }
  235.     /**
  236.      * お気に入り追加.
  237.      *
  238.      * @Route("/products/add_favorite/{id}", name="product_add_favorite", requirements={"id" = "\d+"}, methods={"GET", "POST"})
  239.      */
  240.     public function addFavorite(Request $requestProduct $Product)
  241.     {
  242.         $this->checkVisibility($Product);
  243.         $event = new EventArgs(
  244.             [
  245.                 'Product' => $Product,
  246.             ],
  247.             $request
  248.         );
  249.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_INITIALIZE);
  250.         if ($this->isGranted('ROLE_USER')) {
  251.             $Customer $this->getUser();
  252.             $this->customerFavoriteProductRepository->addFavorite($Customer$Product);
  253.             $this->session->getFlashBag()->set('product_detail.just_added_favorite'$Product->getId());
  254.             $event = new EventArgs(
  255.                 [
  256.                     'Product' => $Product,
  257.                 ],
  258.                 $request
  259.             );
  260.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  261.             return $this->redirectToRoute('product_detail', ['id' => $Product->getId()]);
  262.         } else {
  263.             // 非会員の場合、ログイン画面を表示
  264.             //  ログイン後の画面遷移先を設定
  265.             $this->setLoginTargetPath($this->generateUrl('product_add_favorite', ['id' => $Product->getId()], UrlGeneratorInterface::ABSOLUTE_URL));
  266.             $this->session->getFlashBag()->set('eccube.add.favorite'true);
  267.             $event = new EventArgs(
  268.                 [
  269.                     'Product' => $Product,
  270.                 ],
  271.                 $request
  272.             );
  273.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  274.             return $this->redirectToRoute('mypage_login');
  275.         }
  276.     }
  277.     /**
  278.      * カートに追加.
  279.      *
  280.      * @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
  281.      */
  282.     public function addCart(Request $requestProduct $Product)
  283.     {
  284.         // エラーメッセージの配列
  285.         $errorMessages = [];
  286.         if (!$this->checkVisibility($Product)) {
  287.             throw new NotFoundHttpException();
  288.         }
  289.         $builder $this->formFactory->createNamedBuilder(
  290.             '',
  291.             AddCartType::class,
  292.             null,
  293.             [
  294.                 'product' => $Product,
  295.                 'id_add_product_id' => false,
  296.             ]
  297.         );
  298.         $event = new EventArgs(
  299.             [
  300.                 'builder' => $builder,
  301.                 'Product' => $Product,
  302.             ],
  303.             $request
  304.         );
  305.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE);
  306.         /* @var $form \Symfony\Component\Form\FormInterface */
  307.         $form $builder->getForm();
  308.         $form->handleRequest($request);
  309.         if (!$form->isValid()) {
  310.             throw new NotFoundHttpException();
  311.         }
  312.         $addCartData $form->getData();
  313.         log_info(
  314.             'カート追加処理開始',
  315.             [
  316.                 'product_id' => $Product->getId(),
  317.                 'product_class_id' => $addCartData['product_class_id'],
  318.                 'quantity' => $addCartData['quantity'],
  319.             ]
  320.         );
  321.         // カートへ追加
  322.         $this->cartService->addProduct($addCartData['product_class_id'], $addCartData['quantity']);
  323.         // 明細の正規化
  324.         $Carts $this->cartService->getCarts();
  325.         foreach ($Carts as $Cart) {
  326.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  327.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  328.             if ($result->hasError()) {
  329.                 $this->cartService->removeProduct($addCartData['product_class_id']);
  330.                 foreach ($result->getErrors() as $error) {
  331.                     $errorMessages[] = $error->getMessage();
  332.                 }
  333.             }
  334.             foreach ($result->getWarning() as $warning) {
  335.                 $errorMessages[] = $warning->getMessage();
  336.             }
  337.         }
  338.         $this->cartService->save();
  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.         $event = new EventArgs(
  348.             [
  349.                 'form' => $form,
  350.                 'Product' => $Product,
  351.             ],
  352.             $request
  353.         );
  354.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE);
  355.         if ($event->getResponse() !== null) {
  356.             return $event->getResponse();
  357.         }
  358.         if ($request->isXmlHttpRequest()) {
  359.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  360.             // 初期化
  361.             $messages = [];
  362.             if (empty($errorMessages)) {
  363.                 // エラーが発生していない場合
  364.                 $done true;
  365.                 array_push($messagestrans('front.product.add_cart_complete'));
  366.             } else {
  367.                 // エラーが発生している場合
  368.                 $done false;
  369.                 $messages $errorMessages;
  370.             }
  371.             return $this->json(['done' => $done'messages' => $messages]);
  372.         } else {
  373.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  374.             foreach ($errorMessages as $errorMessage) {
  375.                 $this->addRequestError($errorMessage);
  376.             }
  377.             return $this->redirectToRoute('cart');
  378.         }
  379.     }
  380.     /**
  381.      * ページタイトルの設定
  382.      *
  383.      * @param  array|null $searchData
  384.      *
  385.      * @return str
  386.      */
  387.     protected function getPageTitle($searchData)
  388.     {
  389.         if (isset($searchData['name']) && !empty($searchData['name'])) {
  390.             return trans('front.product.search_result');
  391.         } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
  392.             return $searchData['category_id']->getName();
  393.         } else {
  394.             return trans('front.product.all_products');
  395.         }
  396.     }
  397.     /**
  398.      * 閲覧可能な商品かどうかを判定
  399.      *
  400.      * @param Product $Product
  401.      *
  402.      * @return boolean 閲覧可能な場合はtrue
  403.      */
  404.     protected function checkVisibility(Product $Product)
  405.     {
  406.         $is_admin $this->session->has('_security_admin');
  407.         // 管理ユーザの場合はステータスやオプションにかかわらず閲覧可能.
  408.         if (!$is_admin) {
  409.             // 在庫なし商品の非表示オプションが有効な場合.
  410.             // if ($this->BaseInfo->isOptionNostockHidden()) {
  411.             //     if (!$Product->getStockFind()) {
  412.             //         return false;
  413.             //     }
  414.             // }
  415.             // 公開ステータスでない商品は表示しない.
  416.             if ($Product->getStatus()->getId() !== ProductStatus::DISPLAY_SHOW) {
  417.                 return false;
  418.             }
  419.         }
  420.         return true;
  421.     }
  422.     /**
  423.      * 商品詳細のカテゴリ2表示項目配列作成
  424.      *
  425.      * @param Product $Product
  426.      *
  427.      * @return boolean 閲覧可能な場合はtrue
  428.      */
  429.     protected function setDetailCategory2(Product $Product)
  430.     {
  431.         $categories2 = [];
  432.         
  433.         if(!$Product->hasProductClass()){
  434.             return $categories2;
  435.         }
  436.         foreach($Product->getClassCategories1() as $id1 =>$name1){
  437.             $categories2[$id1]=[];
  438.             
  439.             foreach($Product->getClassCategories2($id1) as $id2 =>$name2){
  440.                 //表示判定
  441.                 $set_flg false;
  442.                 foreach ($Product->getProductClasses() as $product_class_key => $product_class) {
  443.                     // productclassのcategory1とcategory2の値が一致した場合のみループ実行できる
  444.                     if ($id1 == $product_class->getClassCategory1()->getId() && $id2 ==$product_class->getClassCategory2()->getId($id1)) {
  445.                         $all_select_flg true;
  446.                         foreach ($Product->getProductAccessPermissionSchools() as $paps_key => $paps_value) {
  447.                             
  448.                             if(isset($paps_value['productclass']['id'])){
  449.                                 // papsのproduct_class_idが同じ、かつschool_idが同じなら表示
  450.                                 if ($paps_value->getProductClass()->getId() == $product_class->getId()) {
  451.                                     // 一度でもproduct_class_idとpapsのproduct_class_idが一致したら全選択フラグをfalseにする
  452.                                     $all_select_flg false;
  453.                                     if ($paps_value->getSchoolId() == $this->getUser()->getSchoolId()) {
  454.                                         // $(val).val()==product_classのclass_category_id2が一致したら
  455.                                         if ($id2 == $product_class->getClassCategory2()->getId()) {
  456.                                             $set_flg true;
  457.                                         }
  458.                                     }
  459.                                 }
  460.                             }else{
  461.                                 continue;
  462.                             }
  463.                             
  464.                         }
  465.                         if ($all_select_flg) {
  466.                             // 全選択フラグがtrueなら全選択されているproduct_class_id
  467.                             $set_flg true;
  468.                         }
  469.                         
  470.                     }
  471.                 }
  472.                 
  473.                 if($set_flg){
  474.                     $categories2[$id1][$id2]=$name2;
  475.                 }
  476.                 
  477.                 
  478.             }
  479.         }
  480.         return $categories2;
  481.         
  482.     }
  483. }