src/Eccube/Controller/ShoppingController.php line 704

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