src/Eccube/Controller/CartController.php line 87

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