src/Eccube/Controller/ShoppingController.php line 729

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\Customer;
  14. use Eccube\Entity\CustomerAddress;
  15. use Eccube\Entity\Order;
  16. use Eccube\Entity\Shipping;
  17. use Eccube\Event\EccubeEvents;
  18. use Eccube\Event\EventArgs;
  19. use Eccube\Exception\ShoppingException;
  20. use Eccube\Form\Type\Front\CustomerLoginType;
  21. use Eccube\Form\Type\Front\ShoppingShippingType;
  22. use Eccube\Form\Type\Shopping\CustomerAddressType;
  23. use Eccube\Form\Type\Shopping\OrderType;
  24. use Eccube\Repository\OrderRepository;
  25. use Eccube\Repository\TradeLawRepository;
  26. use Eccube\Service\CartService;
  27. use Eccube\Service\MailService;
  28. use Eccube\Service\OrderHelper;
  29. use Eccube\Service\Payment\PaymentDispatcher;
  30. use Eccube\Service\Payment\PaymentMethodInterface;
  31. use Eccube\Service\PurchaseFlow\PurchaseContext;
  32. use Eccube\Service\PurchaseFlow\PurchaseFlow;
  33. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  34. use Symfony\Component\DependencyInjection\ContainerInterface;
  35. use Symfony\Component\Form\FormInterface;
  36. use Symfony\Component\HttpFoundation\Request;
  37. use Symfony\Component\HttpFoundation\Response;
  38. use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException;
  39. use Symfony\Component\RateLimiter\RateLimiterFactory;
  40. use Symfony\Component\Routing\Annotation\Route;
  41. use Symfony\Component\Routing\RouterInterface;
  42. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  43. class ShoppingController extends AbstractShoppingController
  44. {
  45.     /**
  46.      * @var CartService
  47.      */
  48.     protected $cartService;
  49.     /**
  50.      * @var MailService
  51.      */
  52.     protected $mailService;
  53.     /**
  54.      * @var OrderHelper
  55.      */
  56.     protected $orderHelper;
  57.     /**
  58.      * @var OrderRepository
  59.      */
  60.     protected $orderRepository;
  61.     /**
  62.      * @var ContainerInterface
  63.      */
  64.     protected $serviceContainer;
  65.     /**
  66.      * @var TradeLawRepository
  67.      */
  68.     protected TradeLawRepository $tradeLawRepository;
  69.     protected RateLimiterFactory $shoppingConfirmIpLimiter;
  70.     protected RateLimiterFactory $shoppingConfirmCustomerLimiter;
  71.     protected RateLimiterFactory $shoppingCheckoutIpLimiter;
  72.     protected RateLimiterFactory $shoppingCheckoutCustomerLimiter;
  73.     public function __construct(
  74.         CartService $cartService,
  75.         MailService $mailService,
  76.         OrderRepository $orderRepository,
  77.         OrderHelper $orderHelper,
  78.         ContainerInterface $serviceContainer,
  79.         TradeLawRepository $tradeLawRepository,
  80.         RateLimiterFactory $shoppingConfirmIpLimiter,
  81.         RateLimiterFactory $shoppingConfirmCustomerLimiter,
  82.         RateLimiterFactory $shoppingCheckoutIpLimiter,
  83.         RateLimiterFactory $shoppingCheckoutCustomerLimiter
  84.     ) {
  85.         $this->cartService $cartService;
  86.         $this->mailService $mailService;
  87.         $this->orderRepository $orderRepository;
  88.         $this->orderHelper $orderHelper;
  89.         $this->serviceContainer $serviceContainer;
  90.         $this->tradeLawRepository $tradeLawRepository;
  91.         $this->shoppingConfirmIpLimiter $shoppingConfirmIpLimiter;
  92.         $this->shoppingConfirmCustomerLimiter $shoppingConfirmCustomerLimiter;
  93.         $this->shoppingCheckoutIpLimiter $shoppingCheckoutIpLimiter;
  94.         $this->shoppingCheckoutCustomerLimiter $shoppingCheckoutCustomerLimiter;
  95.     }
  96.     /**
  97.      * 注文手続き画面を表示する
  98.      *
  99.      * 未ログインまたはRememberMeログインの場合はログイン画面に遷移させる.
  100.      * ただし、非会員でお客様情報を入力済の場合は遷移させない.
  101.      *
  102.      * カート情報から受注データを生成し, `pre_order_id`でカートと受注の紐付けを行う.
  103.      * 既に受注が生成されている場合(pre_order_idで取得できる場合)は, 受注の生成を行わずに画面を表示する.
  104.      *
  105.      * purchaseFlowの集計処理実行後, warningがある場合はカートど同期をとるため, カートのPurchaseFlowを実行する.
  106.      *
  107.      * @Route("/shopping", name="shopping", methods={"GET"})
  108.      * @Template("Shopping/index.twig")
  109.      */
  110.     public function index(PurchaseFlow $cartPurchaseFlow)
  111.     {
  112.         // ログイン状態のチェック.
  113.         if ($this->orderHelper->isLoginRequired()) {
  114.             log_info('[注文手続] 未ログインもしくはRememberMeログインのため, ログイン画面に遷移します.');
  115.             return $this->redirectToRoute('shopping_login');
  116.         }
  117.         // カートチェック.
  118.         $Cart $this->cartService->getCart();
  119.         if (!($Cart && $this->orderHelper->verifyCart($Cart))) {
  120.             log_info('[注文手続] カートが購入フローへ遷移できない状態のため, カート画面に遷移します.');
  121.             return $this->redirectToRoute('cart');
  122.         }
  123.         // 受注の初期化.
  124.         log_info('[注文手続] 受注の初期化処理を開始します.');
  125.         $Customer $this->getUser() ? $this->getUser() : $this->orderHelper->getNonMember();
  126.         $Order $this->orderHelper->initializeOrder($Cart$Customer);
  127.         // 集計処理.
  128.         log_info('[注文手続] 集計処理を開始します.', [$Order->getId()]);
  129.         $flowResult $this->executePurchaseFlow($Orderfalse);
  130.         $this->entityManager->flush();
  131.         if ($flowResult->hasError()) {
  132.             log_info('[注文手続] Errorが発生したため購入エラー画面へ遷移します.', [$flowResult->getErrors()]);
  133.             return $this->redirectToRoute('shopping_error');
  134.         }
  135.         if ($flowResult->hasWarning()) {
  136.             log_info('[注文手続] Warningが発生しました.', [$flowResult->getWarning()]);
  137.             // 受注明細と同期をとるため, CartPurchaseFlowを実行する
  138.             $cartPurchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  139.             // 注文フローで取得されるカートの入れ替わりを防止する
  140.             // @see https://github.com/EC-CUBE/ec-cube/issues/4293
  141.             $this->cartService->setPrimary($Cart->getCartKey());
  142.         }
  143.         // マイページで会員情報が更新されていれば, Orderの注文者情報も更新する.
  144.         if ($Customer->getId()) {
  145.             $this->orderHelper->updateCustomerInfo($Order$Customer);
  146.             $this->entityManager->flush();
  147.         }
  148.         $activeTradeLaws $this->tradeLawRepository->findBy(['displayOrderScreen' => true], ['sortNo' => 'ASC']);
  149.         $form $this->createForm(OrderType::class, $Order);
  150.         return [
  151.             'form' => $form->createView(),
  152.             'Order' => $Order,
  153.             'activeTradeLaws' => $activeTradeLaws,
  154.         ];
  155.     }
  156.     /**
  157.      * 他画面への遷移を行う.
  158.      *
  159.      * お届け先編集画面など, 他画面へ遷移する際に, フォームの値をDBに保存してからリダイレクトさせる.
  160.      * フォームの`redirect_to`パラメータの値にリダイレクトを行う.
  161.      * `redirect_to`パラメータはpath('遷移先のルーティング')が渡される必要がある.
  162.      *
  163.      * 外部のURLやPathを渡された場合($router->matchで展開出来ない場合)は, 購入エラーとする.
  164.      *
  165.      * プラグインやカスタマイズでこの機能を使う場合は, twig側で以下のように記述してください.
  166.      *
  167.      * <button data-trigger="click" data-path="path('ルーティング')">更新する</button>
  168.      *
  169.      * data-triggerは, click/change/blur等のイベント名を指定してください。
  170.      * data-pathは任意のパラメータです. 指定しない場合, 注文手続き画面へリダイレクトします.
  171.      *
  172.      * @Route("/shopping/redirect_to", name="shopping_redirect_to", methods={"POST"})
  173.      * @Template("Shopping/index.twig")
  174.      */
  175.     public function redirectTo(Request $requestRouterInterface $router)
  176.     {
  177.         // ログイン状態のチェック.
  178.         if ($this->orderHelper->isLoginRequired()) {
  179.             log_info('[リダイレクト] 未ログインもしくはRememberMeログインのため, ログイン画面に遷移します.');
  180.             return $this->redirectToRoute('shopping_login');
  181.         }
  182.         // 受注の存在チェック.
  183.         $preOrderId $this->cartService->getPreOrderId();
  184.         $Order $this->orderHelper->getPurchaseProcessingOrder($preOrderId);
  185.         if (!$Order) {
  186.             log_info('[リダイレクト] 購入処理中の受注が存在しません.');
  187.             return $this->redirectToRoute('shopping_error');
  188.         }
  189.         $form $this->createForm(OrderType::class, $Order);
  190.         $form->handleRequest($request);
  191.         if ($form->isSubmitted() && $form->isValid()) {
  192.             log_info('[リダイレクト] 集計処理を開始します.', [$Order->getId()]);
  193.             $response $this->executePurchaseFlow($Order);
  194.             $this->entityManager->flush();
  195.             if ($response) {
  196.                 return $response;
  197.             }
  198.             $redirectTo $form['redirect_to']->getData();
  199.             if (empty($redirectTo)) {
  200.                 log_info('[リダイレクト] リダイレクト先未指定のため注文手続き画面へ遷移します.');
  201.                 return $this->redirectToRoute('shopping');
  202.             }
  203.             try {
  204.                 // リダイレクト先のチェック.
  205.                 $pattern '/^'.preg_quote($request->getBasePath(), '/').'/';
  206.                 $redirectTo preg_replace($pattern''$redirectTo);
  207.                 $result $router->match($redirectTo);
  208.                 // パラメータのみ抽出
  209.                 $params array_filter($result, function ($key) {
  210.                     return !== \strpos($key'_');
  211.                 }, ARRAY_FILTER_USE_KEY);
  212.                 log_info('[リダイレクト] リダイレクトを実行します.', [$result['_route'], $params]);
  213.                 // pathからurlを再構築してリダイレクト.
  214.                 return $this->redirectToRoute($result['_route'], $params);
  215.             } catch (\Exception $e) {
  216.                 log_info('[リダイレクト] URLの形式が不正です', [$redirectTo$e->getMessage()]);
  217.                 return $this->redirectToRoute('shopping_error');
  218.             }
  219.         }
  220.         $activeTradeLaws $this->tradeLawRepository->findBy(['displayOrderScreen' => true], ['sortNo' => 'ASC']);
  221.         log_info('[リダイレクト] フォームエラーのため, 注文手続き画面を表示します.', [$Order->getId()]);
  222.         return [
  223.             'form' => $form->createView(),
  224.             'Order' => $Order,
  225.             'activeTradeLaws' => $activeTradeLaws,
  226.         ];
  227.     }
  228.     /**
  229.      * 注文確認画面を表示する.
  230.      *
  231.      * ここではPaymentMethod::verifyがコールされます.
  232.      * PaymentMethod::verifyではクレジットカードの有効性チェック等, 注文手続きを進められるかどうかのチェック処理を行う事を想定しています.
  233.      * PaymentMethod::verifyでエラーが発生した場合は, 注文手続き画面へリダイレクトします.
  234.      *
  235.      * @Route("/shopping/confirm", name="shopping_confirm", methods={"POST"})
  236.      * @Template("Shopping/confirm.twig")
  237.      */
  238.     public function confirm(Request $request)
  239.     {
  240.         // ログイン状態のチェック.
  241.         if ($this->orderHelper->isLoginRequired()) {
  242.             log_info('[注文確認] 未ログインもしくはRememberMeログインのため, ログイン画面に遷移します.');
  243.             return $this->redirectToRoute('shopping_login');
  244.         }
  245.         // 受注の存在チェック
  246.         $preOrderId $this->cartService->getPreOrderId();
  247.         $Order $this->orderHelper->getPurchaseProcessingOrder($preOrderId);
  248.         if (!$Order) {
  249.             log_info('[注文確認] 購入処理中の受注が存在しません.', [$preOrderId]);
  250.             return $this->redirectToRoute('shopping_error');
  251.         }
  252.         $activeTradeLaws $this->tradeLawRepository->findBy(['displayOrderScreen' => true], ['sortNo' => 'ASC']);
  253.         $form $this->createForm(OrderType::class, $Order);
  254.         $form->handleRequest($request);
  255.         if ($form->isSubmitted() && $form->isValid()) {
  256.             log_info('[注文確認] 集計処理を開始します.', [$Order->getId()]);
  257.             $response $this->executePurchaseFlow($Order);
  258.             $this->entityManager->flush();
  259.             if ($response) {
  260.                 return $response;
  261.             }
  262.             log_info('[注文確認] IPベースのスロットリングを実行します.');
  263.             $ipLimiter $this->shoppingConfirmIpLimiter->create($request->getClientIp());
  264.             if (!$ipLimiter->consume()->isAccepted()) {
  265.                 log_info('[注文確認] 試行回数制限を超過しました(IPベース)');
  266.                 throw new TooManyRequestsHttpException();
  267.             }
  268.             $Customer $this->getUser();
  269.             if ($Customer instanceof Customer) {
  270.                 log_info('[注文確認] 会員ベースのスロットリングを実行します.');
  271.                 $customerLimiter $this->shoppingConfirmCustomerLimiter->create($Customer->getId());
  272.                 if (!$customerLimiter->consume()->isAccepted()) {
  273.                     log_info('[注文確認] 試行回数制限を超過しました(会員ベース)');
  274.                     throw new TooManyRequestsHttpException();
  275.                 }
  276.             }
  277.             log_info('[注文確認] PaymentMethod::verifyを実行します.', [$Order->getPayment()->getMethodClass()]);
  278.             $paymentMethod $this->createPaymentMethod($Order$form);
  279.             $PaymentResult $paymentMethod->verify();
  280.             if ($PaymentResult) {
  281.                 if (!$PaymentResult->isSuccess()) {
  282.                     $this->entityManager->rollback();
  283.                     foreach ($PaymentResult->getErrors() as $error) {
  284.                         $this->addError($error);
  285.                     }
  286.                     log_info('[注文確認] PaymentMethod::verifyのエラーのため, 注文手続き画面へ遷移します.', [$PaymentResult->getErrors()]);
  287.                     return $this->redirectToRoute('shopping');
  288.                 }
  289.                 $response $PaymentResult->getResponse();
  290.                 if ($response instanceof Response && ($response->isRedirection() || $response->isSuccessful())) {
  291.                     $this->entityManager->flush();
  292.                     log_info('[注文確認] PaymentMethod::verifyが指定したレスポンスを表示します.');
  293.                     return $response;
  294.                 }
  295.             }
  296.             $this->entityManager->flush();
  297.             log_info('[注文確認] 注文確認画面を表示します.');
  298.             return [
  299.                 'form' => $form->createView(),
  300.                 'Order' => $Order,
  301.                 'activeTradeLaws' => $activeTradeLaws,
  302.             ];
  303.         }
  304.         log_info('[注文確認] フォームエラーのため, 注文手続画面を表示します.', [$Order->getId()]);
  305.         $template = new Template([
  306.             'owner' => [$this'confirm'],
  307.             'template' => 'Shopping/index.twig',
  308.         ]);
  309.         $request->attributes->set('_template'$template);
  310.         return [
  311.             'form' => $form->createView(),
  312.             'Order' => $Order,
  313.             'activeTradeLaws' => $activeTradeLaws,
  314.         ];
  315.     }
  316.     /**
  317.      * 注文処理を行う.
  318.      *
  319.      * 決済プラグインによる決済処理および注文の確定処理を行います.
  320.      *
  321.      * @Route("/shopping/checkout", name="shopping_checkout", methods={"POST"})
  322.      * @Template("Shopping/confirm.twig")
  323.      */
  324.     public function checkout(Request $request)
  325.     {
  326.         // ログイン状態のチェック.
  327.         if ($this->orderHelper->isLoginRequired()) {
  328.             log_info('[注文処理] 未ログインもしくはRememberMeログインのため, ログイン画面に遷移します.');
  329.             return $this->redirectToRoute('shopping_login');
  330.         }
  331.         // 受注の存在チェック
  332.         $preOrderId $this->cartService->getPreOrderId();
  333.         $Order $this->orderHelper->getPurchaseProcessingOrder($preOrderId);
  334.         if (!$Order) {
  335.             log_info('[注文処理] 購入処理中の受注が存在しません.', [$preOrderId]);
  336.             return $this->redirectToRoute('shopping_error');
  337.         }
  338.         // フォームの生成.
  339.         $form $this->createForm(OrderType::class, $Order, [
  340.             // 確認画面から注文処理へ遷移する場合は, Orderエンティティで値を引き回すためフォーム項目の定義をスキップする.
  341.             'skip_add_form' => true,
  342.         ]);
  343.         $form->handleRequest($request);
  344.         if ($form->isSubmitted() && $form->isValid()) {
  345.             log_info('[注文処理] 注文処理を開始します.', [$Order->getId()]);
  346.             try {
  347.                 /*
  348.                  * 集計処理
  349.                  */
  350.                 log_info('[注文処理] 集計処理を開始します.', [$Order->getId()]);
  351.                 $response $this->executePurchaseFlow($Order);
  352.                 $this->entityManager->flush();
  353.                 if ($response) {
  354.                     return $response;
  355.                 }
  356.                 log_info('[注文完了] IPベースのスロットリングを実行します.');
  357.                 $ipLimiter $this->shoppingCheckoutIpLimiter->create($request->getClientIp());
  358.                 if (!$ipLimiter->consume()->isAccepted()) {
  359.                     log_info('[注文完了] 試行回数制限を超過しました(IPベース)');
  360.                     throw new TooManyRequestsHttpException();
  361.                 }
  362.                 $Customer $this->getUser();
  363.                 if ($Customer instanceof Customer) {
  364.                     log_info('[注文完了] 会員ベースのスロットリングを実行します.');
  365.                     $customerLimiter $this->shoppingCheckoutCustomerLimiter->create($Customer->getId());
  366.                     if (!$customerLimiter->consume()->isAccepted()) {
  367.                         log_info('[注文完了] 試行回数制限を超過しました(会員ベース)');
  368.                         throw new TooManyRequestsHttpException();
  369.                     }
  370.                 }
  371.                 log_info('[注文処理] PaymentMethodを取得します.', [$Order->getPayment()->getMethodClass()]);
  372.                 $paymentMethod $this->createPaymentMethod($Order$form);
  373.                 /*
  374.                  * 決済実行(前処理)
  375.                  */
  376.                 log_info('[注文処理] PaymentMethod::applyを実行します.');
  377.                 if ($response $this->executeApply($paymentMethod)) {
  378.                     return $response;
  379.                 }
  380.                 /*
  381.                  * 決済実行
  382.                  *
  383.                  * PaymentMethod::checkoutでは決済処理が行われ, 正常に処理出来た場合はPurchaseFlow::commitがコールされます.
  384.                  */
  385.                 log_info('[注文処理] PaymentMethod::checkoutを実行します.');
  386.                 if ($response $this->executeCheckout($paymentMethod)) {
  387.                     return $response;
  388.                 }
  389.                 $this->entityManager->flush();
  390.                 log_info('[注文処理] 注文処理が完了しました.', [$Order->getId()]);
  391.             } catch (ShoppingException $e) {
  392.                 log_error('[注文処理] 購入エラーが発生しました.', [$e->getMessage()]);
  393.                 $this->entityManager->rollback();
  394.                 $this->addError($e->getMessage());
  395.                 return $this->redirectToRoute('shopping_error');
  396.             } catch (\Exception $e) {
  397.                 log_error('[注文処理] 予期しないエラーが発生しました.', [$e->getMessage()]);
  398.                 // $this->entityManager->rollback(); FIXME ユニットテストで There is no active transaction エラーになってしまう
  399.                 $this->addError('front.shopping.system_error');
  400.                 return $this->redirectToRoute('shopping_error');
  401.             }
  402.             // カート削除
  403.             log_info('[注文処理] カートをクリアします.', [$Order->getId()]);
  404.             $this->cartService->clear();
  405.             // 受注IDをセッションにセット
  406.             $this->session->set(OrderHelper::SESSION_ORDER_ID$Order->getId());
  407.             // メール送信
  408.             log_info('[注文処理] 注文メールの送信を行います.', [$Order->getId()]);
  409.             $this->mailService->sendOrderMail($Order);
  410.             $this->entityManager->flush();
  411.             log_info('[注文処理] 注文処理が完了しました. 購入完了画面へ遷移します.', [$Order->getId()]);
  412.             return $this->redirectToRoute('shopping_complete');
  413.         }
  414.         log_info('[注文処理] フォームエラーのため, 購入エラー画面へ遷移します.', [$Order->getId()]);
  415.         return $this->redirectToRoute('shopping_error');
  416.     }
  417.     /**
  418.      * 購入完了画面を表示する.
  419.      *
  420.      * @Route("/shopping/complete", name="shopping_complete", methods={"GET"})
  421.      * @Template("Shopping/complete.twig")
  422.      */
  423.     public function complete(Request $request)
  424.     {
  425.         log_info('[注文完了] 注文完了画面を表示します.');
  426.         // 受注IDを取得
  427.         $orderId $this->session->get(OrderHelper::SESSION_ORDER_ID);
  428.         if (empty($orderId)) {
  429.             log_info('[注文完了] 受注IDを取得できないため, トップページへ遷移します.');
  430.             return $this->redirectToRoute('homepage');
  431.         }
  432.         $Order $this->orderRepository->find($orderId);
  433.         $event = new EventArgs(
  434.             [
  435.                 'Order' => $Order,
  436.             ],
  437.             $request
  438.         );
  439.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_SHOPPING_COMPLETE_INITIALIZE);
  440.         if ($event->getResponse() !== null) {
  441.             return $event->getResponse();
  442.         }
  443.         log_info('[注文完了] 購入フローのセッションをクリアします. ');
  444.         $this->orderHelper->removeSession();
  445.         $hasNextCart = !empty($this->cartService->getCarts());
  446.         log_info('[注文完了] 注文完了画面を表示しました. ', [$hasNextCart]);
  447.         return [
  448.             'Order' => $Order,
  449.             'hasNextCart' => $hasNextCart,
  450.         ];
  451.     }
  452.     /**
  453.      * お届け先選択画面.
  454.      *
  455.      * 会員ログイン時, お届け先を選択する画面を表示する
  456.      * 非会員の場合はこの画面は使用しない。
  457.      *
  458.      * @Route("/shopping/shipping/{id}", name="shopping_shipping", requirements={"id" = "\d+"}, methods={"GET", "POST"})
  459.      * @Template("Shopping/shipping.twig")
  460.      */
  461.     public function shipping(Request $requestShipping $Shipping)
  462.     {
  463.         // ログイン状態のチェック.
  464.         if ($this->orderHelper->isLoginRequired()) {
  465.             return $this->redirectToRoute('shopping_login');
  466.         }
  467.         // 受注の存在チェック
  468.         $preOrderId $this->cartService->getPreOrderId();
  469.         $Order $this->orderHelper->getPurchaseProcessingOrder($preOrderId);
  470.         if (!$Order) {
  471.             return $this->redirectToRoute('shopping_error');
  472.         }
  473.         // 受注に紐づくShippingかどうかのチェック.
  474.         if (!$Order->findShipping($Shipping->getId())) {
  475.             return $this->redirectToRoute('shopping_error');
  476.         }
  477.         $builder $this->formFactory->createBuilder(CustomerAddressType::class, null, [
  478.             'customer' => $this->getUser(),
  479.             'shipping' => $Shipping,
  480.         ]);
  481.         $form $builder->getForm();
  482.         $form->handleRequest($request);
  483.         if ($form->isSubmitted() && $form->isValid()) {
  484.             log_info('お届先情報更新開始', [$Shipping->getId()]);
  485.             /** @var CustomerAddress $CustomerAddress */
  486.             $CustomerAddress $form['addresses']->getData();
  487.             // お届け先情報を更新
  488.             $Shipping->setFromCustomerAddress($CustomerAddress);
  489.             // 合計金額の再計算
  490.             $response $this->executePurchaseFlow($Order);
  491.             $this->entityManager->flush();
  492.             if ($response) {
  493.                 return $response;
  494.             }
  495.             $event = new EventArgs(
  496.                 [
  497.                     'Order' => $Order,
  498.                     'Shipping' => $Shipping,
  499.                 ],
  500.                 $request
  501.             );
  502.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_SHOPPING_SHIPPING_COMPLETE);
  503.             log_info('お届先情報更新完了', [$Shipping->getId()]);
  504.             return $this->redirectToRoute('shopping');
  505.         }
  506.         return [
  507.             'form' => $form->createView(),
  508.             'Customer' => $this->getUser(),
  509.             'shippingId' => $Shipping->getId(),
  510.         ];
  511.     }
  512.     /**
  513.      * お届け先の新規作成または編集画面.
  514.      *
  515.      * 会員時は新しいお届け先を作成し, 作成したお届け先を選択状態にして注文手続き画面へ遷移する.
  516.      * 非会員時は選択されたお届け先の編集を行う.
  517.      *
  518.      * @Route("/shopping/shipping_edit/{id}", name="shopping_shipping_edit", requirements={"id" = "\d+"}, methods={"GET", "POST"})
  519.      * @Template("Shopping/shipping_edit.twig")
  520.      */
  521.     public function shippingEdit(Request $requestShipping $Shipping)
  522.     {
  523.         // ログイン状態のチェック.
  524.         if ($this->orderHelper->isLoginRequired()) {
  525.             return $this->redirectToRoute('shopping_login');
  526.         }
  527.         // 受注の存在チェック
  528.         $preOrderId $this->cartService->getPreOrderId();
  529.         $Order $this->orderHelper->getPurchaseProcessingOrder($preOrderId);
  530.         if (!$Order) {
  531.             return $this->redirectToRoute('shopping_error');
  532.         }
  533.         // 受注に紐づくShippingかどうかのチェック.
  534.         if (!$Order->findShipping($Shipping->getId())) {
  535.             return $this->redirectToRoute('shopping_error');
  536.         }
  537.         $CustomerAddress = new CustomerAddress();
  538.         if ($this->isGranted('IS_AUTHENTICATED_FULLY')) {
  539.             // ログイン時は会員と紐付け
  540.             $CustomerAddress->setCustomer($this->getUser());
  541.         } else {
  542.             // 非会員時はお届け先をセット
  543.             $CustomerAddress->setFromShipping($Shipping);
  544.         }
  545.         $builder $this->formFactory->createBuilder(ShoppingShippingType::class, $CustomerAddress);
  546.         $event = new EventArgs(
  547.             [
  548.                 'builder' => $builder,
  549.                 'Order' => $Order,
  550.                 'Shipping' => $Shipping,
  551.                 'CustomerAddress' => $CustomerAddress,
  552.             ],
  553.             $request
  554.         );
  555.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_SHOPPING_SHIPPING_EDIT_INITIALIZE);
  556.         $form $builder->getForm();
  557.         $form->handleRequest($request);
  558.         if ($form->isSubmitted() && $form->isValid()) {
  559.             log_info('お届け先追加処理開始', ['order_id' => $Order->getId(), 'shipping_id' => $Shipping->getId()]);
  560.             $Shipping->setFromCustomerAddress($CustomerAddress);
  561.             if ($this->isGranted('IS_AUTHENTICATED_FULLY')) {
  562.                 $this->entityManager->persist($CustomerAddress);
  563.             }
  564.             // 合計金額の再計算
  565.             $response $this->executePurchaseFlow($Order);
  566.             $this->entityManager->flush();
  567.             if ($response) {
  568.                 return $response;
  569.             }
  570.             $event = new EventArgs(
  571.                 [
  572.                     'form' => $form,
  573.                     'Shipping' => $Shipping,
  574.                     'CustomerAddress' => $CustomerAddress,
  575.                 ],
  576.                 $request
  577.             );
  578.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_SHOPPING_SHIPPING_EDIT_COMPLETE);
  579.             log_info('お届け先追加処理完了', ['order_id' => $Order->getId(), 'shipping_id' => $Shipping->getId()]);
  580.             return $this->redirectToRoute('shopping');
  581.         }
  582.         return [
  583.             'form' => $form->createView(),
  584.             'shippingId' => $Shipping->getId(),
  585.         ];
  586.     }
  587.     /**
  588.      * ログイン画面.
  589.      *
  590.      * @Route("/shopping/login", name="shopping_login", methods={"GET"})
  591.      * @Template("Shopping/login.twig")
  592.      */
  593.     public function login(Request $requestAuthenticationUtils $authenticationUtils)
  594.     {
  595.         if ($this->isGranted('IS_AUTHENTICATED_FULLY')) {
  596.             return $this->redirectToRoute('shopping');
  597.         }
  598.         /* @var $form \Symfony\Component\Form\FormInterface */
  599.         $builder $this->formFactory->createNamedBuilder(''CustomerLoginType::class);
  600.         if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  601.             $Customer $this->getUser();
  602.             if ($Customer) {
  603.                 $builder->get('login_email')->setData($Customer->getEmail());
  604.             }
  605.         }
  606.         $event = new EventArgs(
  607.             [
  608.                 'builder' => $builder,
  609.             ],
  610.             $request
  611.         );
  612.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_SHOPPING_LOGIN_INITIALIZE);
  613.         $form $builder->getForm();
  614.         return [
  615.             'error' => $authenticationUtils->getLastAuthenticationError(),
  616.             'form' => $form->createView(),
  617.         ];
  618.     }
  619.     /**
  620.      * 購入エラー画面.
  621.      *
  622.      * @Route("/shopping/error", name="shopping_error", methods={"GET"})
  623.      * @Template("Shopping/shopping_error.twig")
  624.      */
  625.     public function error(Request $requestPurchaseFlow $cartPurchaseFlow)
  626.     {
  627.         // 受注とカートのずれを合わせるため, カートのPurchaseFlowをコールする.
  628.         $Cart $this->cartService->getCart();
  629.         if (null !== $Cart) {
  630.             $cartPurchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  631.             $this->cartService->setPreOrderId(null);
  632.             $this->cartService->save();
  633.         }
  634.         $event = new EventArgs(
  635.             [],
  636.             $request
  637.         );
  638.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_SHOPPING_SHIPPING_ERROR_COMPLETE);
  639.         if ($event->getResponse() !== null) {
  640.             return $event->getResponse();
  641.         }
  642.         return [];
  643.     }
  644.     /**
  645.      * PaymentMethodをコンテナから取得する.
  646.      *
  647.      * @param Order $Order
  648.      * @param FormInterface $form
  649.      *
  650.      * @return PaymentMethodInterface
  651.      */
  652.     private function createPaymentMethod(Order $OrderFormInterface $form)
  653.     {
  654.         $PaymentMethod $this->serviceContainer->get($Order->getPayment()->getMethodClass());
  655.         $PaymentMethod->setOrder($Order);
  656.         $PaymentMethod->setFormType($form);
  657.         return $PaymentMethod;
  658.     }
  659.     /**
  660.      * PaymentMethod::applyを実行する.
  661.      *
  662.      * @param PaymentMethodInterface $paymentMethod
  663.      *
  664.      * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
  665.      */
  666.     protected function executeApply(PaymentMethodInterface $paymentMethod)
  667.     {
  668.         $dispatcher $paymentMethod->apply(); // 決済処理中.
  669.         // リンク式決済のように他のサイトへ遷移する場合などは, dispatcherに処理を移譲する.
  670.         if ($dispatcher instanceof PaymentDispatcher) {
  671.             $response $dispatcher->getResponse();
  672.             $this->entityManager->flush();
  673.             // dispatcherがresponseを保持している場合はresponseを返す
  674.             if ($response instanceof Response && ($response->isRedirection() || $response->isSuccessful())) {
  675.                 log_info('[注文処理] PaymentMethod::applyが指定したレスポンスを表示します.');
  676.                 return $response;
  677.             }
  678.             // forwardすることも可能.
  679.             if ($dispatcher->isForward()) {
  680.                 log_info('[注文処理] PaymentMethod::applyによりForwardします.',
  681.                     [$dispatcher->getRoute(), $dispatcher->getPathParameters(), $dispatcher->getQueryParameters()]);
  682.                 return $this->forwardToRoute($dispatcher->getRoute(), $dispatcher->getPathParameters(),
  683.                     $dispatcher->getQueryParameters());
  684.             } else {
  685.                 log_info('[注文処理] PaymentMethod::applyによりリダイレクトします.',
  686.                     [$dispatcher->getRoute(), $dispatcher->getPathParameters(), $dispatcher->getQueryParameters()]);
  687.                 return $this->redirectToRoute($dispatcher->getRoute(),
  688.                     array_merge($dispatcher->getPathParameters(), $dispatcher->getQueryParameters()));
  689.             }
  690.         }
  691.     }
  692.     /**
  693.      * PaymentMethod::checkoutを実行する.
  694.      *
  695.      * @param PaymentMethodInterface $paymentMethod
  696.      *
  697.      * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response|null
  698.      */
  699.     protected function executeCheckout(PaymentMethodInterface $paymentMethod)
  700.     {
  701.         $PaymentResult $paymentMethod->checkout();
  702.         $response $PaymentResult->getResponse();
  703.         // PaymentResultがresponseを保持している場合はresponseを返す
  704.         if ($response instanceof Response && ($response->isRedirection() || $response->isSuccessful())) {
  705.             $this->entityManager->flush();
  706.             log_info('[注文処理] PaymentMethod::checkoutが指定したレスポンスを表示します.');
  707.             return $response;
  708.         }
  709.         // エラー時はロールバックして購入エラーとする.
  710.         if (!$PaymentResult->isSuccess()) {
  711.             $this->entityManager->rollback();
  712.             foreach ($PaymentResult->getErrors() as $error) {
  713.                 $this->addError($error);
  714.             }
  715.             log_info('[注文処理] PaymentMethod::checkoutのエラーのため, 購入エラー画面へ遷移します.', [$PaymentResult->getErrors()]);
  716.             return $this->redirectToRoute('shopping_error');
  717.         }
  718.         return null;
  719.     }
  720. }