app/Plugin/JoolenEntryOrderCompleted4/EntryOrderCompletedEvent.php line 192

Open in your IDE?
  1. <?php
  2. /*
  3.  * Plugin Name: JoolenEntryOrderCompleted4
  4.  *
  5.  * Copyright(c) joolen inc. All Rights Reserved.
  6.  *
  7.  * https://www.joolen.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 Plugin\JoolenEntryOrderCompleted4;
  13. use Eccube\Common\Constant;
  14. use Eccube\Entity\BaseInfo;
  15. use Eccube\Entity\Master\CustomerStatus;
  16. use Eccube\Event\EccubeEvents;
  17. use Eccube\Event\EventArgs;
  18. use Eccube\Form\Type\Front\EntryType;
  19. use Eccube\Repository\BaseInfoRepository;
  20. use Eccube\Repository\CustomerRepository;
  21. use Eccube\Repository\Master\CustomerStatusRepository;
  22. use Eccube\Repository\OrderRepository;
  23. use Eccube\Repository\PluginRepository;
  24. use Eccube\Service\CartService;
  25. use Eccube\Service\MailService;
  26. use Eccube\Service\OrderHelper;
  27. use Symfony\Component\DependencyInjection\ContainerInterface;
  28. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  29. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  30. use Plugin\JoolenEntryOrderCompleted4\Service\EntryOrderCompletedService;
  31. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  32. use Symfony\Component\HttpKernel\Event\PostResponseEvent;
  33. use Symfony\Component\HttpKernel\KernelEvents;
  34. use Symfony\Bundle\FrameworkBundle\Controller\ControllerTrait;
  35. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  36. use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
  37. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  38. use Doctrine\ORM\EntityManagerInterface;
  39. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  40. use Symfony\Component\HttpFoundation\Request;
  41. use Symfony\Component\HttpFoundation\RedirectResponse;
  42. class EntryOrderCompletedEvent implements EventSubscriberInterface
  43. {
  44.     use ControllerTrait;
  45.     /**
  46.      * @var ContainerInterface
  47.      */
  48.     private $container;
  49.     /**
  50.      * @var MailService
  51.      */
  52.     protected $mailService;
  53.     /**
  54.      * @var BaseInfo
  55.      */
  56.     protected $BaseInfo;
  57.     /**
  58.      * @var CustomerRepository
  59.      */
  60.     protected $customerRepository;
  61.     /**
  62.      * @var CustomerStatusRepository
  63.      */
  64.     protected $customerStatusRepository;
  65.     /**
  66.      * @var OrderRepository
  67.      */
  68.     protected $orderRepository;
  69.     /**
  70.      * @var PluginRepository
  71.      */
  72.     protected $pluginRepository;
  73.     /**
  74.      * @var EntryOrderCompletedService
  75.      */
  76.     protected $entryOrderCompletedService;
  77.     /**
  78.      * @var \Eccube\Service\CartService
  79.      */
  80.     protected $cartService;
  81.     /**
  82.      * @var EncoderFactoryInterface
  83.      */
  84.     protected $encoderFactory;
  85.     /**
  86.      * @var TokenStorageInterface
  87.      */
  88.     protected $tokenStorage;
  89.     /**
  90.      * @var $session
  91.      */
  92.     private $session;
  93.     /**
  94.      * @var EntityManagerInterface
  95.      */
  96.     private $entityManager;
  97.     /**
  98.      * @var OrderHelper
  99.      */
  100.     protected $orderHelper;
  101.     /**
  102.      * @var string 受注IDを保持するセッションのキー
  103.      */
  104.     const PLG_SESSION_ORDER_ID 'plugin.entry_order_completed.order.id';
  105.     /**
  106.      * EntryOrderCompletedEvent constructor.
  107.      *
  108.      * @param ContainerInterface $container
  109.      * @param MailService $mailService
  110.      * @param BaseInfoRepository $baseInfoRepository
  111.      * @param CustomerRepository $customerRepository
  112.      * @param CustomerStatusRepository $customerStatusRepository
  113.      * @param OrderRepository $orderRepository
  114.      * @param PluginRepository $pluginRepository
  115.      * @param EntryOrderCompletedService $entryOrderCompletedService
  116.      * @param CartService $cartService
  117.      * @param EncoderFactoryInterface $encoderFactory
  118.      * @param TokenStorageInterface $tokenStorage
  119.      * @param SessionInterface $session
  120.      * @param EntityManagerInterface $entityManager
  121.      * @param OrderHelper $orderHelper
  122.      * @throws \Exception
  123.      */
  124.     public function __construct(
  125.         ContainerInterface $container,
  126.         MailService $mailService,
  127.         BaseInfoRepository $baseInfoRepository,
  128.         CustomerRepository $customerRepository,
  129.         CustomerStatusRepository $customerStatusRepository,
  130.         OrderRepository $orderRepository,
  131.         PluginRepository $pluginRepository,
  132.         EntryOrderCompletedService $entryOrderCompletedService,
  133.         CartService $cartService,
  134.         EncoderFactoryInterface $encoderFactory,
  135.         TokenStorageInterface $tokenStorage,
  136.         SessionInterface $session,
  137.         EntityManagerInterface $entityManager,
  138.         OrderHelper $orderHelper
  139.     ) {
  140.         $this->container $container;
  141.         $this->mailService $mailService;
  142.         $this->BaseInfo $baseInfoRepository->get();
  143.         $this->customerRepository $customerRepository;
  144.         $this->customerStatusRepository $customerStatusRepository;
  145.         $this->orderRepository $orderRepository;
  146.         $this->pluginRepository $pluginRepository;
  147.         $this->entryOrderCompletedService $entryOrderCompletedService;
  148.         $this->cartService $cartService;
  149.         $this->encoderFactory $encoderFactory;
  150.         $this->tokenStorage $tokenStorage;
  151.         $this->session $session;
  152.         $this->entityManager $entityManager;
  153.         $this->orderHelper $orderHelper;
  154.     }
  155.     /**
  156.      * @return array
  157.      */
  158.     public static function getSubscribedEvents()
  159.     {
  160.         return [
  161.             KernelEvents::REQUEST => 'onKernelRequest',
  162.             EccubeEvents::FRONT_SHOPPING_COMPLETE_INITIALIZE => 'onShoppingCompleteInitialize'
  163.         ];
  164.     }
  165.     /**
  166.      * Kernel request listener callback.
  167.      *
  168.      * @param GetResponseEvent $event
  169.      */
  170.     public function onKernelRequest(GetResponseEvent $event)
  171.     {
  172.         $request $event->getRequest();
  173.         $pathInfo $request->getPathInfo();
  174.         // ShoppingController::complete以外は処理しない
  175.         if (preg_match('/.*\/shopping\/complete/'$pathInfo) == 0) {
  176.             return null;
  177.         }
  178.         // トップページへリダイレクトさせないためにセッションに受注IDをセット
  179.         if ($request->getMethod() === 'POST') {
  180.             $plgOrderId $this->session->get(self::PLG_SESSION_ORDER_ID);
  181.             $this->session->set(OrderHelper::SESSION_ORDER_ID$plgOrderId);
  182.         }
  183.     }
  184.     public function onShoppingCompleteInitialize(EventArgs $event)
  185.     {
  186.         $hasHiddenItemsError false;
  187.         /** @var $Order \Eccube\Entity\Order */
  188.         $Order $event->getArgument("Order");
  189.         // ゲスト購入でなければ後続処理はしない
  190.         if(!is_null($Order->getCustomer())) {
  191.             return;
  192.         }
  193.         // 会員登録されているEmailであれば後続処理はしない
  194.         $existingCustomer $this->customerRepository->findBy(['email' => $Order->getEmail()]);
  195.         if (count($existingCustomer) > 0) {
  196.             return;
  197.         }
  198.         // セッションから受注IDを取得し退避
  199.         $orderId $this->session->get(OrderHelper::SESSION_ORDER_ID);
  200.         $this->session->set(self::PLG_SESSION_ORDER_ID$orderId);
  201.         log_info('[注文完了] 購入フローのセッションをクリアします. ');
  202.         $this->orderHelper->removeSession();
  203.         /** @var $Customer \Eccube\Entity\Customer */
  204.         $Customer $this->customerRepository->newCustomer();
  205.         $Customer $this->entryOrderCompletedService->setFromOrder($Customer,$Order);
  206.         /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  207.         $formFactory $this->container->get('form.factory');
  208.         $builder $formFactory->createBuilder(EntryType::class, $Customer);
  209.         /* @var $form \Symfony\Component\Form\FormInterface */
  210.         $form $builder->getForm();
  211.         $request $event->getRequest();
  212.         $form->handleRequest($request);
  213.         if ($form->isSubmitted() && $form->isValid()) {
  214.             log_info('会員登録開始');
  215.             $encoder $this->encoderFactory->getEncoder($Customer);
  216.             $salt $encoder->createSalt();
  217.             $password $encoder->encodePassword($Customer->getPassword(), $salt);
  218.             $secretKey $this->customerRepository->getUniqueSecretKey();
  219.             $Customer
  220.                 ->setSalt($salt)
  221.                 ->setPassword($password)
  222.                 ->setSecretKey($secretKey)
  223.                 ->setPoint(0);
  224.             dump($Customer);die;
  225.             $this->entityManager->persist($Customer);
  226.             $this->entityManager->flush();
  227.             log_info('会員登録完了');
  228.             $activateFlg $this->BaseInfo->isOptionCustomerActivate();
  229.             $activateUrl $this->generateUrl('entry_activate', ['secret_key' => $Customer->getSecretKey()], UrlGeneratorInterface::ABSOLUTE_URL);
  230.             // 仮会員設定が有効な場合は、確認メールを送信し完了画面表示.
  231.             if ($activateFlg) {
  232.                 // メール送信
  233.                 $this->mailService->sendCustomerConfirmMail($Customer$activateUrl);
  234.                 log_info('仮会員登録完了画面へリダイレクト');
  235.                 $this->session->remove(self::PLG_SESSION_ORDER_ID);
  236.                 $response = new RedirectResponse($this->generateUrl('entry_complete', [], UrlGeneratorInterface::ABSOLUTE_URL));
  237.                 return $event->setResponse($response);
  238.             }
  239.             // 仮会員設定が無効な場合は、会員登録を完了させる.
  240.             // 4.0.3 以前の処理
  241.             if( Constant::VERSION <='4.0.3') {
  242.                 log_info('本会員登録画面へリダイレクト');
  243.                 $this->session->remove(self::PLG_SESSION_ORDER_ID);
  244.                 $response = new RedirectResponse($activateUrl);
  245.                 return $event->setResponse($response);
  246.             }
  247.             $qtyInCart $this->entryActivate($request$Customer->getSecretKey(), $event);
  248.             $this->session->remove(self::PLG_SESSION_ORDER_ID);
  249.             // URLを変更するため完了画面にリダイレクト
  250.             $response = new RedirectResponse($this->generateUrl('entry_activate', [
  251.                 'secret_key' => $Customer->getSecretKey(),
  252.                 'qtyInCart' => $qtyInCart,
  253.             ], UrlGeneratorInterface::ABSOLUTE_URL));
  254.             return $event->setResponse($response);
  255.         }
  256.         dump(1);die;
  257.         foreach ($form->getErrors(true) as $error) {
  258.             if ($error->getCause()) {
  259.                 preg_match_all(
  260.                     '/\[.*?\]/',
  261.                     $error->getCause()->getPropertyPath(),
  262.                     $matches);
  263.                 $element str_replace(['[',']'],'',array_pop($matches[0]));
  264.             }
  265.             if (!in_array($element, ['first','second''user_policy_check'])) {
  266.                 $hasHiddenItemsError true;
  267.                 break;
  268.             }
  269.         }
  270.         // $hasNextCart = !empty($this->cartService->getCarts());
  271.         // $event->setResponse($this->render("Shopping/complete.twig", [
  272.         //     'Order' => $Order,
  273.         //     'hasNextCart' => $hasNextCart,
  274.         //     'plgForm' => $form->createView(),
  275.         //     'hasHiddenItemsError' => $hasHiddenItemsError,
  276.         // ]));
  277.     }
  278.     /**
  279.      * 会員登録処理を行う
  280.      *
  281.      * @param Request $request
  282.      * @param $secret_key
  283.      * @param EventArgs $event
  284.      * @return \Eccube\Entity\Cart|mixed
  285.      */
  286.     private function entryActivate(Request $request$secret_key,EventArgs $event)
  287.     {
  288.         log_info('本会員登録開始');
  289.         $Customer $this->customerRepository->getProvisionalCustomerBySecretKey($secret_key);
  290.         if (is_null($Customer)) {
  291.             throw new HttpException\NotFoundHttpException();
  292.         }
  293.         $CustomerStatus $this->customerStatusRepository->find(CustomerStatus::REGULAR);
  294.         $Customer->setStatus($CustomerStatus);
  295.         $this->entityManager->persist($Customer);
  296.         $this->entityManager->flush();
  297.         log_info('本会員登録完了');
  298.         $event->setArgument('Customer'$Customer);
  299.         // MEMO: 新規会員登録時ポイント付与プラグインとの連携
  300.         $JoolenPointsForMemberRegistration4 $this->pluginRepository->findOneBy(['code' => 'JoolenPointsForMemberRegistration4''enabled' => 1]);
  301.         if ($JoolenPointsForMemberRegistration4) {
  302.             $JoolenPointsForMemberRegistration4Event $this->container->get('Plugin\JoolenPointsForMemberRegistration4\Event');
  303.             $JoolenPointsForMemberRegistration4Event->onEntryActivateComplete($event);
  304.         }
  305.         // MEMO: 新規会員登録時クーポン付与プラグインとの連携
  306.         $JoolenCouponForMemberRegistration4 $this->pluginRepository->findOneBy(['code' => 'JoolenCouponForMemberRegistration4''enabled' => 1]);
  307.         if ($JoolenCouponForMemberRegistration4) {
  308.             $JoolenCouponForMemberRegistration4Event $this->container->get('Plugin\JoolenCouponForMemberRegistration4\Event');
  309.             $JoolenCouponForMemberRegistration4Event->onEntryActivateComplete($event);
  310.         }
  311.         // メール送信
  312.         $this->mailService->sendCustomerCompleteMail($Customer);
  313.         // Assign session carts into customer carts
  314.         $Carts $this->cartService->getCarts();
  315.         $qtyInCart 0;
  316.         foreach ($Carts as $Cart) {
  317.             $qtyInCart += $Cart->getTotalQuantity();
  318.         }
  319.         // 本会員登録してログイン状態にする
  320.         $token = new UsernamePasswordToken($Customernull'customer', ['ROLE_USER']);
  321.         $this->tokenStorage->setToken($token);
  322.         $request->getSession()->migrate(true);
  323.         if ($qtyInCart) {
  324.             $this->cartService->save();
  325.         }
  326.         log_info('ログイン済に変更', [$this->getUser()->getId()]);
  327.         return $qtyInCart;
  328.     }
  329. }