src/Eccube/Controller/CartController.php line 117

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.         // カートを取得して明細の正規化を実行
  73.         $Carts $this->cartService->getCarts();
  74.         $this->execPurchaseFlow($Carts);
  75.         // TODO itemHolderから取得できるように
  76.         $least = [];
  77.         $quantity = [];
  78.         $isDeliveryFree = [];
  79.         $totalPrice 0;
  80.         $totalQuantity 0;
  81.         foreach ($Carts as $Cart) {
  82.             $quantity[$Cart->getCartKey()] = 0;
  83.             $isDeliveryFree[$Cart->getCartKey()] = false;
  84.             if ($this->baseInfo->getDeliveryFreeQuantity()) {
  85.                 if ($this->baseInfo->getDeliveryFreeQuantity() > $Cart->getQuantity()) {
  86.                     $quantity[$Cart->getCartKey()] = $this->baseInfo->getDeliveryFreeQuantity() - $Cart->getQuantity();
  87.                 } else {
  88.                     $isDeliveryFree[$Cart->getCartKey()] = true;
  89.                 }
  90.             }
  91.             if ($this->baseInfo->getDeliveryFreeAmount()) {
  92.                 if (!$isDeliveryFree[$Cart->getCartKey()] && $this->baseInfo->getDeliveryFreeAmount() <= $Cart->getTotalPrice()) {
  93.                     $isDeliveryFree[$Cart->getCartKey()] = true;
  94.                 } else {
  95.                     $least[$Cart->getCartKey()] = $this->baseInfo->getDeliveryFreeAmount() - $Cart->getTotalPrice();
  96.                 }
  97.             }
  98.             $totalPrice += $Cart->getTotalPrice();
  99.             $totalQuantity += $Cart->getQuantity();
  100.         }
  101.         // カートが分割された時のセッション情報を削除
  102.         $request->getSession()->remove(OrderHelper::SESSION_CART_DIVIDE_FLAG);
  103.         return [
  104.             'totalPrice' => $totalPrice,
  105.             'totalQuantity' => $totalQuantity,
  106.             // 空のカートを削除し取得し直す
  107.             'Carts' => $this->cartService->getCarts(true),
  108.             'least' => $least,
  109.             'quantity' => $quantity,
  110.             'is_delivery_free' => $isDeliveryFree,
  111.         ];
  112.     }
  113.     /**
  114.      * @param $Carts
  115.      *
  116.      * @return \Symfony\Component\HttpFoundation\RedirectResponse|null
  117.      */
  118.     protected function execPurchaseFlow($Carts)
  119.     {
  120.         /** @var PurchaseFlowResult[] $flowResults */
  121.         $flowResults array_map(function ($Cart) {
  122.             $purchaseContext = new PurchaseContext($Cart$this->getUser());
  123.             return $this->purchaseFlow->validate($Cart$purchaseContext);
  124.         }, $Carts);
  125.         // 復旧不可のエラーが発生した場合はカートをクリアして再描画
  126.         $hasError false;
  127.         foreach ($flowResults as $result) {
  128.             if ($result->hasError()) {
  129.                 $hasError true;
  130.                 foreach ($result->getErrors() as $error) {
  131.                     $this->addRequestError($error->getMessage());
  132.                 }
  133.             }
  134.         }
  135.         if ($hasError) {
  136.             $this->cartService->clear();
  137.             return $this->redirectToRoute('cart');
  138.         }
  139.         $this->cartService->save();
  140.         foreach ($flowResults as $index => $result) {
  141.             foreach ($result->getWarning() as $warning) {
  142.                 if ($Carts[$index]->getItems()->count() > 0) {
  143.                     $cart_key $Carts[$index]->getCartKey();
  144.                     $this->addRequestError($warning->getMessage(), "front.cart.${cart_key}");
  145.                 } else {
  146.                     // キーが存在しない場合はグローバルにエラーを表示する
  147.                     $this->addRequestError($warning->getMessage());
  148.                 }
  149.             }
  150.         }
  151.         return null;
  152.     }
  153.     /**
  154.      * カート明細の個数変更
  155.      *
  156.      * @Route(
  157.      *     path="/cart/change_num/",
  158.      *     name="cart_change_num",
  159.      *     methods={"GET"},
  160.      * )
  161.      */
  162.     public function ChangeNum(Request $request){
  163.         $productClassId $request->get("class_id");
  164.         $num $request->get("num");
  165.         /** @var ProductClass $ProductClass */
  166.         $ProductClass $this->productClassRepository->find($productClassId);
  167.         if (is_null($ProductClass)) {
  168.             log_info('商品が存在しないため、カート画面へredirect');
  169.             return $this->redirectToRoute('cart');
  170.         }
  171.         // 明細数の変更
  172.         $this->cartService->addProduct($ProductClass$num);
  173.         // カートを取得して明細の正規化を実行
  174.         $Carts $this->cartService->getCarts();
  175.         $this->execPurchaseFlow($Carts);
  176.         log_info('カートの数量変更処理終了');
  177.         return $this->redirectToRoute('cart');
  178.     }
  179.     
  180.     /**
  181.      * カート明細の加算/減算/削除を行う.
  182.      *
  183.      * - 加算
  184.      *      - 明細の個数を1増やす
  185.      * - 減算
  186.      *      - 明細の個数を1減らす
  187.      *      - 個数が0になる場合は、明細を削除する
  188.      * - 削除
  189.      *      - 明細を削除する
  190.      *
  191.      * @Route(
  192.      *     path="/cart/{operation}/{productClassId}",
  193.      *     name="cart_handle_item",
  194.      *     methods={"PUT"},
  195.      *     requirements={
  196.      *          "operation": "up|down|remove",
  197.      *          "productClassId": "\d+"
  198.      *     }
  199.      * )
  200.      */
  201.     public function handleCartItem($operation$productClassId)
  202.     {
  203.         log_info('カート明細操作開始', ['operation' => $operation'product_class_id' => $productClassId]);
  204.         $this->isTokenValid();
  205.         /** @var ProductClass $ProductClass */
  206.         $ProductClass $this->productClassRepository->find($productClassId);
  207.         if (is_null($ProductClass)) {
  208.             log_info('商品が存在しないため、カート画面へredirect', ['operation' => $operation'product_class_id' => $productClassId]);
  209.             return $this->redirectToRoute('cart');
  210.         }
  211.         // 明細の増減・削除
  212.         switch ($operation) {
  213.             case 'up':
  214.                 $this->cartService->addProduct($ProductClass1);
  215.                 break;
  216.             case 'down':
  217.                 $this->cartService->addProduct($ProductClass, -1);
  218.                 break;
  219.             case 'remove':
  220.                 $this->cartService->removeProduct($ProductClass);
  221.                 break;
  222.         }
  223.         // カートを取得して明細の正規化を実行
  224.         $Carts $this->cartService->getCarts();
  225.         $this->execPurchaseFlow($Carts);
  226.         log_info('カート演算処理終了', ['operation' => $operation'product_class_id' => $productClassId]);
  227.         return $this->redirectToRoute('cart');
  228.     }
  229.     /**
  230.      * カートをロック状態に設定し、購入確認画面へ遷移する.
  231.      *
  232.      * @Route("/cart/buystep/{cart_key}", name="cart_buystep", requirements={"cart_key" = "[a-zA-Z0-9]+[_][\x20-\x7E]+"}, methods={"GET"})
  233.      */
  234.     public function buystep(Request $request$cart_key)
  235.     {
  236.         $Carts $this->cartService->getCart();
  237.         if (!is_object($Carts)) {
  238.             return $this->redirectToRoute('cart');
  239.         }
  240.         // FRONT_CART_BUYSTEP_INITIALIZE
  241.         $event = new EventArgs(
  242.             [],
  243.             $request
  244.         );
  245.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_CART_BUYSTEP_INITIALIZE);
  246.         $this->cartService->setPrimary($cart_key);
  247.         $this->cartService->save();
  248.         // FRONT_CART_BUYSTEP_COMPLETE
  249.         $event = new EventArgs(
  250.             [],
  251.             $request
  252.         );
  253.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_CART_BUYSTEP_COMPLETE);
  254.         if ($event->hasResponse()) {
  255.             return $event->getResponse();
  256.         }
  257.         return $this->redirectToRoute('shopping');
  258.     }
  259. }