app/Customize/Controller/DetailBibController.php line 124

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\AbstractController;
  14. use Eccube\Entity\BaseInfo;
  15. use Eccube\Entity\Master\ProductStatus;
  16. use Eccube\Entity\Product;
  17. use Eccube\Event\EccubeEvents;
  18. use Eccube\Event\EventArgs;
  19. use Eccube\Form\Type\AddCartType;
  20. use Eccube\Form\Type\SearchProductType;
  21. use Eccube\Repository\BaseInfoRepository;
  22. use Eccube\Repository\CustomerFavoriteProductRepository;
  23. use Eccube\Repository\Master\ProductListMaxRepository;
  24. use Eccube\Repository\ProductRepository;
  25. use Eccube\Service\CartService;
  26. use Eccube\Service\PurchaseFlow\PurchaseContext;
  27. use Eccube\Service\PurchaseFlow\PurchaseFlow;
  28. use Knp\Bundle\PaginatorBundle\Pagination\SlidingPagination;
  29. use Knp\Component\Pager\PaginatorInterface;
  30. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  31. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  32. use Symfony\Component\HttpFoundation\Request;
  33. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  34. use Symfony\Component\Routing\Annotation\Route;
  35. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  36. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  37. use Symfony\Component\Form\Extension\Core\Type\HiddenType;
  38. class DetailBibController extends AbstractController
  39. {
  40.      /**
  41.      * @var PurchaseFlow
  42.      */
  43.     protected $purchaseFlow;
  44.     /**
  45.      * @var CustomerFavoriteProductRepository
  46.      */
  47.     protected $customerFavoriteProductRepository;
  48.     /**
  49.      * @var CartService
  50.      */
  51.     protected $cartService;
  52.     /**
  53.      * @var ProductRepository
  54.      */
  55.     protected $productRepository;
  56.     /**
  57.      * @var BaseInfo
  58.      */
  59.     protected $BaseInfo;
  60.     /**
  61.      * @var AuthenticationUtils
  62.      */
  63.     protected $helper;
  64.     /**
  65.      * @var ProductListMaxRepository
  66.      */
  67.     protected $productListMaxRepository;
  68.     private $title '';
  69.    /**
  70.      * ProductController constructor.
  71.      *
  72.      * @param PurchaseFlow $cartPurchaseFlow
  73.      * @param CustomerFavoriteProductRepository $customerFavoriteProductRepository
  74.      * @param CartService $cartService
  75.      * @param ProductRepository $productRepository
  76.      * @param BaseInfoRepository $baseInfoRepository
  77.      * @param AuthenticationUtils $helper
  78.      * @param ProductListMaxRepository $productListMaxRepository
  79.      */
  80.     public function __construct(
  81.         PurchaseFlow $cartPurchaseFlow,
  82.         CustomerFavoriteProductRepository $customerFavoriteProductRepository,
  83.         CartService $cartService,
  84.         ProductRepository $productRepository,
  85.         BaseInfoRepository $baseInfoRepository,
  86.         AuthenticationUtils $helper,
  87.         ProductListMaxRepository $productListMaxRepository
  88.     ) {
  89.         $this->purchaseFlow $cartPurchaseFlow;
  90.         $this->customerFavoriteProductRepository $customerFavoriteProductRepository;
  91.         $this->cartService $cartService;
  92.         $this->productRepository $productRepository;
  93.         $this->BaseInfo $baseInfoRepository->get();
  94.         $this->helper $helper;
  95.         $this->productListMaxRepository $productListMaxRepository;
  96.     }
  97.     /**
  98.      * BIB詳細画面
  99.      * @Route("/products/bib_detail/{id}/{id2}", name="bib_detail", methods={"GET"},  requirements={"id" = "\d+","id2" = "\d+"})
  100.      * @Template("Product/bib_detail.twig")
  101.      * @ParamConverter("Product", options={"id" = "id", "repository_method" = "findWithSortedClassCategories"})
  102.      * @ParamConverter("Product2", options={"id" = "id2", "repository_method" = "findWithSortedClassCategories"})
  103.      * 
  104.      * @param Request $request
  105.      * @param Product $Product
  106.      * @param Product $Product2
  107.      *
  108.      * @return array
  109.      */
  110.     public function index(Request $requestProduct $ProductProduct $Product2)
  111.     {
  112.         // if (!$this->checkVisibility($Product) || !$this->checkVisibility($Product2)) {
  113.         //     throw new NotFoundHttpException();
  114.         // }
  115.     
  116.         $ids = [];
  117.         $ids[] = $Product->getId();
  118.         $ids[] = $Product2->getId();
  119.         $ProductsAndClassCategories $this->productRepository->findProductsWithSortedClassCategories($ids'p.id');
  120.     
  121.         // addCart form
  122.         $forms = [];
  123.         /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  124.         $builder $this->formFactory->createNamedBuilder(
  125.             '',
  126.             AddCartType::class,
  127.             null,
  128.             [
  129.                 'product' => $ProductsAndClassCategories[$Product->getId()],
  130.                 'allow_extra_fields' => true,
  131.             ]
  132.         );
  133.         $addCartForm $builder->getForm();
  134.         $forms[$Product->getId()] = $addCartForm->createView();
  135.         /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  136.         $builder $this->formFactory->createNamedBuilder(
  137.             '',
  138.             AddCartType::class,
  139.             null,
  140.             [
  141.                 'product' => $ProductsAndClassCategories[$Product2->getId()],
  142.                 'allow_extra_fields' => true,
  143.             ]
  144.         );
  145.         $addCartForm $builder->getForm();
  146.         $forms[$Product2->getId()] = $addCartForm->createView();
  147.     
  148.         $is_favorite false;
  149.         $is_favorite2 false;
  150.         if ($this->isGranted('ROLE_USER')) {
  151.             $Customer $this->getUser();
  152.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  153.             $is_favorite2 $this->customerFavoriteProductRepository->isFavorite($Customer$Product2);
  154.         }
  155.     
  156.         return [
  157.             'forms' => $forms,
  158.             'title' => $this->title,
  159.             'subtitle' => $Product->getName(),
  160.             'form' => $builder->getForm()->createView(),
  161.             'Product' => $Product,
  162.             'is_favorite' => $is_favorite,
  163.             'Product2' => $Product2,
  164.             'is_favorite2' => $is_favorite2,
  165.         ];
  166.     }
  167.     /**
  168.      * カートに追加.
  169.      *
  170.       * @Route("/products/bib_product_add_cart/{id}", name="bib_product_add_cart", methods={"POST"})
  171.      */
  172.     public function addCart(Request $request$id)
  173.     {
  174.         // $productId = $request->request->get('product_id');
  175.         $productId $id;
  176.         $Product $this->productRepository->find($productId);
  177.         // エラーメッセージの配列
  178.         $errorMessages = [];
  179.         if (!$this->checkVisibility($Product)) {
  180.             throw new NotFoundHttpException();
  181.         }
  182.         $builder $this->formFactory->createNamedBuilder(
  183.             '',
  184.             AddCartType::class,
  185.             null,
  186.             [
  187.                 'product' => $Product,
  188.                 'id_add_product_id' => false,
  189.             ]
  190.         );
  191.         $event = new EventArgs(
  192.             [
  193.                 'builder' => $builder,
  194.                 'Product' => $Product,
  195.             ],
  196.             $request
  197.         );
  198.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE);
  199.         /* @var $form \Symfony\Component\Form\FormInterface */
  200.         $form $builder->getForm();
  201.         $form->handleRequest($request);
  202.         // フォームが送信されたかどうか、そして有効かどうかを確認
  203.         if (!$form->isSubmitted() || !$form->isValid()) {
  204.             throw new NotFoundHttpException('The form is not submitted or not valid.');
  205.         }
  206.         $addCartData $form->getData();
  207.         log_info(
  208.             'カート追加処理開始',
  209.             [
  210.                 'product_id' => $Product->getId(),
  211.                 'product_class_id' => $addCartData['product_class_id'],
  212.                 'quantity' => $addCartData['quantity'],
  213.             ]
  214.         );
  215.         // カートへ追加
  216.         $this->cartService->addProduct($addCartData['product_class_id'], $addCartData['quantity']);
  217.         // 明細の正規化
  218.         $Carts $this->cartService->getCarts();
  219.         foreach ($Carts as $Cart) {
  220.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  221.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  222.             if ($result->hasError()) {
  223.                 $this->cartService->removeProduct($addCartData['product_class_id']);
  224.                 foreach ($result->getErrors() as $error) {
  225.                     $errorMessages[] = $error->getMessage();
  226.                 }
  227.             }
  228.             foreach ($result->getWarning() as $warning) {
  229.                 $errorMessages[] = $warning->getMessage();
  230.             }
  231.         }
  232.         $this->cartService->save();
  233.         log_info(
  234.             'カート追加処理完了',
  235.             [
  236.                 'product_id' => $Product->getId(),
  237.                 'product_class_id' => $addCartData['product_class_id'],
  238.                 'quantity' => $addCartData['quantity'],
  239.             ]
  240.         );
  241.         $event = new EventArgs(
  242.             [
  243.                 'form' => $form,
  244.                 'Product' => $Product,
  245.             ],
  246.             $request
  247.         );
  248.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE);
  249.         if ($event->getResponse() !== null) {
  250.             return $event->getResponse();
  251.         }
  252.         if ($request->isXmlHttpRequest()) {
  253.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  254.             // 初期化
  255.             $messages = [];
  256.             if (empty($errorMessages)) {
  257.                 // エラーが発生していない場合
  258.                 $done true;
  259.                 array_push($messagestrans('front.product.add_cart_complete'));
  260.             } else {
  261.                 // エラーが発生している場合
  262.                 $done false;
  263.                 $messages $errorMessages;
  264.             }
  265.             return $this->json(['done' => $done'messages' => $messages]);
  266.         } else {
  267.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  268.             foreach ($errorMessages as $errorMessage) {
  269.                 $this->addRequestError($errorMessage);
  270.             }
  271.             return $this->redirectToRoute('cart');
  272.         }
  273.     }
  274.     /**
  275.      * ページタイトルの設定
  276.      *
  277.      * @param  array|null $searchData
  278.      *
  279.      * @return str
  280.      */
  281.     protected function getPageTitle($searchData)
  282.     {
  283.         if (isset($searchData['name']) && !empty($searchData['name'])) {
  284.             return trans('front.product.search_result');
  285.         } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
  286.             return $searchData['category_id']->getName();
  287.         } else {
  288.             return trans('front.product.all_products');
  289.         }
  290.     }
  291.     /**
  292.      * 閲覧可能な商品かどうかを判定
  293.      *
  294.      * @param Product $Product
  295.      *
  296.      * @return boolean 閲覧可能な場合はtrue
  297.      */
  298.     protected function checkVisibility(Product $Product)
  299.     {
  300.         $is_admin $this->session->has('_security_admin');
  301.         // 管理ユーザの場合はステータスやオプションにかかわらず閲覧可能.
  302.         if (!$is_admin) {
  303.             // 在庫なし商品の非表示オプションが有効な場合.
  304.             // if ($this->BaseInfo->isOptionNostockHidden()) {
  305.             //     if (!$Product->getStockFind()) {
  306.             //         return false;
  307.             //     }
  308.             // }
  309.             // 公開ステータスでない商品は表示しない.
  310.             if ($Product->getStatus()->getId() !== ProductStatus::DISPLAY_SHOW) {
  311.                 return false;
  312.             }
  313.         }
  314.         return true;
  315.     }
  316.     /**
  317.      * お気に入り追加.
  318.      *
  319.      * @Route("/products/bib_add_favorite/{id}", name="product_bib_add_favorite", requirements={"id" = "\d+"}, methods={"GET", "POST"})
  320.      */
  321.     public function addFavorite(Request $requestProduct $Product)
  322.     {
  323.         $this->checkVisibility($Product);
  324.         $event = new EventArgs(
  325.             [
  326.                 'Product' => $Product,
  327.             ],
  328.             $request
  329.         );
  330.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_INITIALIZE);
  331.         if ($this->isGranted('ROLE_USER')) {
  332.             $Customer $this->getUser();
  333.             $this->customerFavoriteProductRepository->addFavorite($Customer$Product);
  334.             $this->session->getFlashBag()->set('product_detail.just_added_favorite'$Product->getId());
  335.             $event = new EventArgs(
  336.                 [
  337.                     'Product' => $Product,
  338.                 ],
  339.                 $request
  340.             );
  341.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  342.             return $this->redirectToRoute('bib_detail', [
  343.                 'id' => 40,
  344.                 'id2' => 18,
  345.             ]);
  346.         } else {
  347.             // 非会員の場合、ログイン画面を表示
  348.             //  ログイン後の画面遷移先を設定
  349.             $this->setLoginTargetPath($this->generateUrl('product_add_favorite', ['id' => $Product->getId()], UrlGeneratorInterface::ABSOLUTE_URL));
  350.             $this->session->getFlashBag()->set('eccube.add.favorite'true);
  351.             $event = new EventArgs(
  352.                 [
  353.                     'Product' => $Product,
  354.                 ],
  355.                 $request
  356.             );
  357.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  358.             return $this->redirectToRoute('mypage_login');
  359.         }
  360.     }
  361. }