src/Eccube/Controller/ProductController.php line 143

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. //dump($pagination);
  170.         return [
  171.             'subtitle' => $this->getPageTitle($searchData),
  172.             'pagination' => $pagination,
  173.             'search_form' => $searchForm->createView(),
  174.             'forms' => $forms,
  175.             'Category' => $Category,
  176.         ];
  177.     }
  178.     /**
  179.      * 商品詳細画面.
  180.      *
  181.      * @Route("/products/detail/{id}", name="product_detail", methods={"GET"}, requirements={"id" = "\d+"})
  182.      * @Template("Product/detail.twig")
  183.      * @ParamConverter("Product", options={"repository_method" = "findWithSortedClassCategories"})
  184.      *
  185.      * @param Request $request
  186.      * @param Product $Product
  187.      *
  188.      * @return array
  189.      */
  190.     public function detail(Request $requestProduct $Product)
  191.     {
  192.         if (!$this->checkVisibility($Product)) {
  193.             throw new NotFoundHttpException();
  194.         }
  195.         $builder $this->formFactory->createNamedBuilder(
  196.             '',
  197.             AddCartType::class,
  198.             null,
  199.             [
  200.                 'product' => $Product,
  201.                 'id_add_product_id' => false,
  202.             ]
  203.         );
  204.         $event = new EventArgs(
  205.             [
  206.                 'builder' => $builder,
  207.                 'Product' => $Product,
  208.             ],
  209.             $request
  210.         );
  211.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE);
  212.         $is_favorite false;
  213.         if ($this->isGranted('ROLE_USER')) {
  214.             $Customer $this->getUser();
  215.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  216.         }
  217.         
  218.         foreach($Product->getProductClasses() as $ProductClasse){
  219.             dumpproperty_exists($ProductClasse 'defult_delivery_date_days') );
  220.             if( property_exists($ProductClasse 'defult_delivery_date_days') ){
  221.                 
  222.             }else{
  223.                 $ProductClasse->defult_delivery_date_days $ProductClasse->getDeliveryDateDays();
  224.             }
  225.             dump($ProductClasse);
  226.         }
  227.         
  228.         return [
  229.             'title' => $this->title,
  230.             'subtitle' => $Product->getName(),
  231.             'form' => $builder->getForm()->createView(),
  232.             'Product' => $Product,
  233.             'is_favorite' => $is_favorite,
  234.         ];
  235.     }
  236.     /**
  237.      * お気に入り追加.
  238.      *
  239.      * @Route("/products/add_favorite/{id}", name="product_add_favorite", requirements={"id" = "\d+"}, methods={"GET", "POST"})
  240.      */
  241.     public function addFavorite(Request $requestProduct $Product)
  242.     {
  243.         $this->checkVisibility($Product);
  244.         $event = new EventArgs(
  245.             [
  246.                 'Product' => $Product,
  247.             ],
  248.             $request
  249.         );
  250.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_INITIALIZE);
  251.         if ($this->isGranted('ROLE_USER')) {
  252.             $Customer $this->getUser();
  253.             $this->customerFavoriteProductRepository->addFavorite($Customer$Product);
  254.             $this->session->getFlashBag()->set('product_detail.just_added_favorite'$Product->getId());
  255.             $event = new EventArgs(
  256.                 [
  257.                     'Product' => $Product,
  258.                 ],
  259.                 $request
  260.             );
  261.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  262.             return $this->redirectToRoute('product_detail', ['id' => $Product->getId()]);
  263.         } else {
  264.             // 非会員の場合、ログイン画面を表示
  265.             //  ログイン後の画面遷移先を設定
  266.             $this->setLoginTargetPath($this->generateUrl('product_add_favorite', ['id' => $Product->getId()], UrlGeneratorInterface::ABSOLUTE_URL));
  267.             $this->session->getFlashBag()->set('eccube.add.favorite'true);
  268.             $event = new EventArgs(
  269.                 [
  270.                     'Product' => $Product,
  271.                 ],
  272.                 $request
  273.             );
  274.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  275.             return $this->redirectToRoute('mypage_login');
  276.         }
  277.     }
  278.     /**
  279.      * カートに追加.
  280.      *
  281.      * @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
  282.      */
  283.     public function addCart(Request $requestProduct $Product)
  284.     {
  285.         dump('addCart');
  286.         // エラーメッセージの配列
  287.         $errorMessages = [];
  288.         if (!$this->checkVisibility($Product)) {
  289.             throw new NotFoundHttpException();
  290.         }
  291.         $builder $this->formFactory->createNamedBuilder(
  292.             '',
  293.             AddCartType::class,
  294.             null,
  295.             [
  296.                 'product' => $Product,
  297.                 'id_add_product_id' => false,
  298.             ]
  299.         );
  300.         $event = new EventArgs(
  301.             [
  302.                 'builder' => $builder,
  303.                 'Product' => $Product,
  304.             ],
  305.             $request
  306.         );
  307.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE);
  308.         /* @var $form \Symfony\Component\Form\FormInterface */
  309.         $form $builder->getForm();
  310.         $form->handleRequest($request);
  311.         if (!$form->isValid()) {
  312.             throw new NotFoundHttpException();
  313.         }
  314.         $addCartData $form->getData();
  315.         log_info(
  316.             'カート追加処理開始',
  317.             [
  318.                 'product_id' => $Product->getId(),
  319.                 'product_class_id' => $addCartData['product_class_id'],
  320.                 'quantity' => $addCartData['quantity'],
  321.             ]
  322.         );
  323.         // カートへ追加
  324.         $this->cartService->addProduct($addCartData['product_class_id'], $addCartData['quantity']);
  325.         // 明細の正規化
  326.         $Carts $this->cartService->getCarts();
  327.         foreach ($Carts as $Cart) {
  328.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  329.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  330.             if ($result->hasError()) {
  331.                 $this->cartService->removeProduct($addCartData['product_class_id']);
  332.                 foreach ($result->getErrors() as $error) {
  333.                     $errorMessages[] = $error->getMessage();
  334.                 }
  335.             }
  336.             foreach ($result->getWarning() as $warning) {
  337.                 $errorMessages[] = $warning->getMessage();
  338.             }
  339.         }
  340.         $this->cartService->save();
  341.         log_info(
  342.             'カート追加処理完了',
  343.             [
  344.                 'product_id' => $Product->getId(),
  345.                 'product_class_id' => $addCartData['product_class_id'],
  346.                 'quantity' => $addCartData['quantity'],
  347.             ]
  348.         );
  349.         $event = new EventArgs(
  350.             [
  351.                 'form' => $form,
  352.                 'Product' => $Product,
  353.             ],
  354.             $request
  355.         );
  356.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE);
  357.         if ($event->getResponse() !== null) {
  358.             return $event->getResponse();
  359.         }
  360.         if ($request->isXmlHttpRequest()) {
  361.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  362.             // 初期化
  363.             $messages = [];
  364.             if (empty($errorMessages)) {
  365.                 // エラーが発生していない場合
  366.                 $done true;
  367.                 array_push($messagestrans('front.product.add_cart_complete'));
  368.             } else {
  369.                 // エラーが発生している場合
  370.                 $done false;
  371.                 $messages $errorMessages;
  372.             }
  373.             return $this->json(['done' => $done'messages' => $messages]);
  374.         } else {
  375.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  376.             foreach ($errorMessages as $errorMessage) {
  377.                 $this->addRequestError($errorMessage);
  378.             }
  379.             return $this->redirectToRoute('cart');
  380.         }
  381.     }
  382.     /**
  383.      * ページタイトルの設定
  384.      *
  385.      * @param  array|null $searchData
  386.      *
  387.      * @return str
  388.      */
  389.     protected function getPageTitle($searchData)
  390.     {
  391.         if (isset($searchData['name']) && !empty($searchData['name'])) {
  392.             return trans('front.product.search_result');
  393.         } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
  394.             return $searchData['category_id']->getName();
  395.         } else {
  396.             return trans('front.product.all_products');
  397.         }
  398.     }
  399.     /**
  400.      * 閲覧可能な商品かどうかを判定
  401.      *
  402.      * @param Product $Product
  403.      *
  404.      * @return boolean 閲覧可能な場合はtrue
  405.      */
  406.     protected function checkVisibility(Product $Product)
  407.     {
  408.         $is_admin $this->session->has('_security_admin');
  409.         // 管理ユーザの場合はステータスやオプションにかかわらず閲覧可能.
  410.         if (!$is_admin) {
  411.             // 在庫なし商品の非表示オプションが有効な場合.
  412.             // if ($this->BaseInfo->isOptionNostockHidden()) {
  413.             //     if (!$Product->getStockFind()) {
  414.             //         return false;
  415.             //     }
  416.             // }
  417.             // 公開ステータスでない商品は表示しない.
  418.             if ($Product->getStatus()->getId() !== ProductStatus::DISPLAY_SHOW) {
  419.                 return false;
  420.             }
  421.         }
  422.         return true;
  423.     }
  424. }