app/Customize/Controller/ProductController.php line 160

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