app/Customize/Controller/ShoppingController.php line 751

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