app/Customize/Controller/ProductController.php line 155

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