app/Customize/Controller/CustomizeProductController.php line 140

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