src/Eccube/Controller/CartController.php line 79

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\ProductClass;
  15. use Eccube\Event\EccubeEvents;
  16. use Eccube\Event\EventArgs;
  17. use Eccube\Repository\BaseInfoRepository;
  18. use Eccube\Repository\ProductClassRepository;
  19. use Eccube\Service\CartService;
  20. use Eccube\Service\OrderHelper;
  21. use Eccube\Service\PurchaseFlow\PurchaseContext;
  22. use Eccube\Service\PurchaseFlow\PurchaseFlow;
  23. use Eccube\Service\PurchaseFlow\PurchaseFlowResult;
  24. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  25. use Symfony\Component\HttpFoundation\Request;
  26. use Symfony\Component\Routing\Annotation\Route;
  27. class CartController extends AbstractController
  28. {
  29.     /**
  30.      * @var ProductClassRepository
  31.      */
  32.     protected $productClassRepository;
  33.     /**
  34.      * @var CartService
  35.      */
  36.     protected $cartService;
  37.     /**
  38.      * @var PurchaseFlow
  39.      */
  40.     protected $purchaseFlow;
  41.     /**
  42.      * @var BaseInfo
  43.      */
  44.     protected $baseInfo;
  45.     /**
  46.      * CartController constructor.
  47.      *
  48.      * @param ProductClassRepository $productClassRepository
  49.      * @param CartService $cartService
  50.      * @param PurchaseFlow $cartPurchaseFlow
  51.      * @param BaseInfoRepository $baseInfoRepository
  52.      */
  53.     public function __construct(
  54.         ProductClassRepository $productClassRepository,
  55.         CartService $cartService,
  56.         PurchaseFlow $cartPurchaseFlow,
  57.         BaseInfoRepository $baseInfoRepository
  58.     ) {
  59.         $this->productClassRepository $productClassRepository;
  60.         $this->cartService $cartService;
  61.         $this->purchaseFlow $cartPurchaseFlow;
  62.         $this->baseInfo $baseInfoRepository->get();
  63.     }
  64.     /**
  65.      * カート画面.
  66.      *
  67.      * @Route("/cart", name="cart", methods={"GET"})
  68.      * @Template("Cart/index.twig")
  69.      */
  70.     public function index(Request $request)
  71.     {
  72.         // from cart to login
  73. //        if (!$this->isGranted('ROLE_USER')) {
  74. //            return $this->redirectToRoute('mypage_login');
  75. //        }
  76.         // カートを取得して明細の正規化を実行
  77.         $Carts $this->cartService->getCarts();
  78.         $this->execPurchaseFlow($Carts);
  79.         // TODO itemHolderから取得できるように
  80.         $least = [];
  81.         $quantity = [];
  82.         $isDeliveryFree = [];
  83.         $totalPrice 0;
  84.         $totalQuantity 0;
  85.         foreach ($Carts as $Cart) {
  86.             $quantity[$Cart->getCartKey()] = 0;
  87.             $isDeliveryFree[$Cart->getCartKey()] = false;
  88.             if ($this->baseInfo->getDeliveryFreeQuantity()) {
  89.                 if ($this->baseInfo->getDeliveryFreeQuantity() > $Cart->getQuantity()) {
  90.                     $quantity[$Cart->getCartKey()] = $this->baseInfo->getDeliveryFreeQuantity() - $Cart->getQuantity();
  91.                 } else {
  92.                     $isDeliveryFree[$Cart->getCartKey()] = true;
  93.                 }
  94.             }
  95.             if ($this->baseInfo->getDeliveryFreeAmount()) {
  96.                 if (!$isDeliveryFree[$Cart->getCartKey()] && $this->baseInfo->getDeliveryFreeAmount() <= $Cart->getTotalPrice()) {
  97.                     $isDeliveryFree[$Cart->getCartKey()] = true;
  98.                     $Cart->setDeliveryFeeTotal(0);
  99.                 } else {
  100.                     $least[$Cart->getCartKey()] = $this->baseInfo->getDeliveryFreeAmount() - $Cart->getTotalPrice();
  101.                 }
  102.             }
  103.             $totalPrice += $Cart->getTotalPrice();
  104.             $totalQuantity += $Cart->getQuantity();
  105.         }
  106.         // カートが分割された時のセッション情報を削除
  107.         $request->getSession()->remove(OrderHelper::SESSION_CART_DIVIDE_FLAG);
  108.         return [
  109.             'totalPrice' => $totalPrice,
  110.             'totalQuantity' => $totalQuantity,
  111.             // 空のカートを削除し取得し直す
  112.             'Carts' => $this->cartService->getCarts(true),
  113.             'least' => $least,
  114.             'quantity' => $quantity,
  115.             'is_delivery_free' => $isDeliveryFree,
  116.         ];
  117.     }
  118.     /**
  119.      * @param $Carts
  120.      *
  121.      * @return \Symfony\Component\HttpFoundation\RedirectResponse|null
  122.      */
  123.     protected function execPurchaseFlow($Carts)
  124.     {
  125.         /** @var PurchaseFlowResult[] $flowResults */
  126.         $flowResults array_map(function ($Cart) {
  127.             $purchaseContext = new PurchaseContext($Cart$this->getUser());
  128.             return $this->purchaseFlow->validate($Cart$purchaseContext);
  129.         }, $Carts);
  130.         // 復旧不可のエラーが発生した場合はカートをクリアして再描画
  131.         $hasError false;
  132.         foreach ($flowResults as $result) {
  133.             if ($result->hasError()) {
  134.                 $hasError true;
  135.                 foreach ($result->getErrors() as $error) {
  136.                     $this->addRequestError($error->getMessage());
  137.                 }
  138.             }
  139.         }
  140.         if ($hasError) {
  141.             $this->cartService->clear();
  142.             return $this->redirectToRoute('cart');
  143.         }
  144.         $this->cartService->save();
  145.         foreach ($flowResults as $index => $result) {
  146.             foreach ($result->getWarning() as $warning) {
  147.                 if ($Carts[$index]->getItems()->count() > 0) {
  148.                     $cart_key $Carts[$index]->getCartKey();
  149.                     $this->addRequestError($warning->getMessage(), "front.cart.${cart_key}");
  150.                 } else {
  151.                     // キーが存在しない場合はグローバルにエラーを表示する
  152.                     $this->addRequestError($warning->getMessage());
  153.                 }
  154.             }
  155.         }
  156.         return null;
  157.     }
  158.     /**
  159.      * カート明細の加算/減算/削除を行う.
  160.      *
  161.      * - 加算
  162.      *      - 明細の個数を1増やす
  163.      * - 減算
  164.      *      - 明細の個数を1減らす
  165.      *      - 個数が0になる場合は、明細を削除する
  166.      * - 削除
  167.      *      - 明細を削除する
  168.      *
  169.      * @Route(
  170.      *     path="/cart/{operation}/{productClassId}",
  171.      *     name="cart_handle_item",
  172.      *     methods={"PUT"},
  173.      *     requirements={
  174.      *          "operation": "up|down|remove",
  175.      *          "productClassId": "\d+"
  176.      *     }
  177.      * )
  178.      */
  179.     public function handleCartItem($operation$productClassId)
  180.     {
  181.         log_info('カート明細操作開始', ['operation' => $operation'product_class_id' => $productClassId]);
  182.         $this->isTokenValid();
  183.         /** @var ProductClass $ProductClass */
  184.         $ProductClass $this->productClassRepository->find($productClassId);
  185.         if (is_null($ProductClass)) {
  186.             log_info('商品が存在しないため、カート画面へredirect', ['operation' => $operation'product_class_id' => $productClassId]);
  187.             return $this->redirectToRoute('cart');
  188.         }
  189.         // 明細の増減・削除
  190.         switch ($operation) {
  191.             case 'up':
  192.                 $this->cartService->addProduct($ProductClass1);
  193.                 break;
  194.             case 'down':
  195.                 $this->cartService->addProduct($ProductClass, -1);
  196.                 break;
  197.             case 'remove':
  198.                 $this->cartService->removeProduct($ProductClass);
  199.                 break;
  200.         }
  201.         // カートを取得して明細の正規化を実行
  202.         $Carts $this->cartService->getCarts();
  203.         $this->execPurchaseFlow($Carts);
  204.         log_info('カート演算処理終了', ['operation' => $operation'product_class_id' => $productClassId]);
  205.         return $this->redirectToRoute('cart');
  206.     }
  207.     /**
  208.      * カートをロック状態に設定し、購入確認画面へ遷移する.
  209.      *
  210.      * @Route("/cart/buystep/{cart_key}", name="cart_buystep", requirements={"cart_key" = "[a-zA-Z0-9]+[_][\x20-\x7E]+"}, methods={"GET"})
  211.      */
  212.     public function buystep(Request $request$cart_key)
  213.     {
  214.         $Carts $this->cartService->getCart();
  215.         if (!is_object($Carts)) {
  216.             return $this->redirectToRoute('cart');
  217.         }
  218.         // FRONT_CART_BUYSTEP_INITIALIZE
  219.         $event = new EventArgs(
  220.             [],
  221.             $request
  222.         );
  223.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_CART_BUYSTEP_INITIALIZE);
  224.         $this->cartService->setPrimary($cart_key);
  225.         $this->cartService->save();
  226.         // FRONT_CART_BUYSTEP_COMPLETE
  227.         $event = new EventArgs(
  228.             [],
  229.             $request
  230.         );
  231.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_CART_BUYSTEP_COMPLETE);
  232.         if ($event->hasResponse()) {
  233.             return $event->getResponse();
  234.         }
  235.         return $this->redirectToRoute('shopping');
  236.     }
  237. }