<?php
/*
* This file is part of EC-CUBE
*
* Copyright(c) EC-CUBE CO.,LTD. All Rights Reserved.
*
* http://www.ec-cube.co.jp/
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eccube\Controller;
use Eccube\Entity\BaseInfo;
use Eccube\Entity\Master\CustomerStatus;
use Eccube\Event\EccubeEvents;
use Eccube\Event\EventArgs;
use Eccube\Form\Type\Front\EntryType;
use Eccube\Repository\BaseInfoRepository;
use Eccube\Repository\CustomerRepository;
use Eccube\Repository\Master\CustomerStatusRepository;
use Eccube\Repository\PageRepository;
use Eccube\Service\CartService;
use Eccube\Service\MailService;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception as HttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Component\Form\FormError;
//----代理店カスタマイズ------
//代理店名の取得はカスタムリポジトリを使用
//----------
use Customize\Repository\CustomizeCustomerRepository;
class EntryController extends AbstractController
{
/**
* @var CustomerStatusRepository
*/
protected $customerStatusRepository;
/**
* @var ValidatorInterface
*/
protected $recursiveValidator;
/**
* @var MailService
*/
protected $mailService;
/**
* @var BaseInfo
*/
protected $BaseInfo;
/**
* @var CustomerRepository
*/
protected $customerRepository;
/**
* @var EncoderFactoryInterface
*/
protected $encoderFactory;
/**
* @var TokenStorageInterface
*/
protected $tokenStorage;
/**
* @var \Eccube\Service\CartService
*/
protected $cartService;
/**
* @var PageRepository
*/
protected $pageRepository;
//----代理店カスタマイズ------
//代理店名の取得はカスタムリポジトリを使用
//----------
private $customizeCustomerRepository;
/**
* EntryController constructor.
*
* @param CartService $cartService
* @param CustomerStatusRepository $customerStatusRepository
* @param MailService $mailService
* @param BaseInfoRepository $baseInfoRepository
* @param CustomerRepository $customerRepository
* @param EncoderFactoryInterface $encoderFactory
* @param ValidatorInterface $validatorInterface
* @param TokenStorageInterface $tokenStorage
*/
public function __construct(
CartService $cartService,
CustomerStatusRepository $customerStatusRepository,
MailService $mailService,
BaseInfoRepository $baseInfoRepository,
CustomerRepository $customerRepository,
EncoderFactoryInterface $encoderFactory,
ValidatorInterface $validatorInterface,
TokenStorageInterface $tokenStorage,
PageRepository $pageRepository,
CustomizeCustomerRepository $customizeCustomerRepository
) {
$this->customerStatusRepository = $customerStatusRepository;
$this->mailService = $mailService;
$this->BaseInfo = $baseInfoRepository->get();
$this->customerRepository = $customerRepository;
$this->encoderFactory = $encoderFactory;
$this->recursiveValidator = $validatorInterface;
$this->tokenStorage = $tokenStorage;
$this->cartService = $cartService;
$this->pageRepository = $pageRepository;
$this->customizeCustomerRepository = $customizeCustomerRepository;
}
/**
* 会員登録画面.
*
* @Route("/entry", name="entry", methods={"GET", "POST"})
* @Route("/entry", name="entry_confirm", methods={"GET", "POST"})
* @Template("Entry/index.twig")
*/
public function index(Request $request)
{
if ($this->isGranted('ROLE_USER')) {
log_info('認証済のためログイン処理をスキップ');
return $this->redirectToRoute('mypage');
}
/** @var $Customer \Eccube\Entity\Customer */
$Customer = $this->customerRepository->newCustomer();
/* @var $builder \Symfony\Component\Form\FormBuilderInterface */
$builder = $this->formFactory->createBuilder(EntryType::class, $Customer);
$event = new EventArgs(
[
'builder' => $builder,
'Customer' => $Customer,
],
$request
);
$this->eventDispatcher->dispatch($event, EccubeEvents::FRONT_ENTRY_INDEX_INITIALIZE);
/* @var $form \Symfony\Component\Form\FormInterface */
$form = $builder->getForm();
$form->handleRequest($request);
// refパラメータを取得
$ref = $request->query->get('ref');
if ($ref) {
// refがGETパラメータにある場合はセッションに保存
$this->session->set('entry_ref', $ref);
} else {
// GETパラメータにrefがない場合はセッションから取得
$ref = $this->session->get('entry_ref');
}
$formAction = $this->generateUrl('entry', ['ref' => $ref]);
// 英語環境でのカナバリデーションエラーを除去
$this->removeKanaValidationErrorsForEnglish($form);
$agencyCode = $Customer->getAgencyCode();
// 代理店紹介コードのチェック
if (!empty($agencyCode)) {
$AgencyId = $this->customizeCustomerRepository->findAgencyIdByAgencyCode($agencyCode);
if (!$AgencyId) {
$form->get('agencyCode')->addError(new FormError('form_error.not_found_agency_code'));
return [
'form' => $form->createView(),
'form_action' => $formAction,
'ref' => $ref,
];
}
}
if ($form->isSubmitted() && $form->isValid()) {
// 英語環境の場合、カナフィールドを空に設定
$this->handleEnglishKanaData($Customer);
switch ($request->get('mode')) {
case 'confirm':
log_info('会員登録確認開始');
log_info('会員登録確認完了');
return $this->render(
'Entry/confirm.twig',
[
'ref' => $ref,
'form' => $form->createView(),
'Page' => $this->pageRepository->getPageByRoute('entry_confirm'),
]
);
case 'complete':
log_info('会員登録開始');
$encoder = $this->encoderFactory->getEncoder($Customer);
$salt = $encoder->createSalt();
$password = $encoder->encodePassword($Customer->getPlainPassword(), $salt);
$secretKey = $this->customerRepository->getUniqueSecretKey();
$Customer
->setSalt($salt)
->setPassword($password)
->setSecretKey($secretKey)
->setPoint(0);
$this->entityManager->persist($Customer);
$this->entityManager->flush();
log_info('会員登録完了');
// 会員登録完了時にrefをセッションから削除
$this->session->remove('entry_ref');
$event = new EventArgs(
[
'form' => $form,
'Customer' => $Customer,
],
$request
);
$this->eventDispatcher->dispatch($event, EccubeEvents::FRONT_ENTRY_INDEX_COMPLETE);
$activateFlg = $this->BaseInfo->isOptionCustomerActivate();
if ($activateFlg) {
$activateUrl = $this->generateUrl('entry_activate', ['secret_key' => $Customer->getSecretKey()], UrlGeneratorInterface::ABSOLUTE_URL);
$this->mailService->sendCustomerConfirmMail($Customer, $activateUrl);
if ($event->hasResponse()) {
return $event->getResponse();
}
log_info('仮会員登録完了画面へリダイレクト');
return $this->redirectToRoute('entry_complete');
} else {
$qtyInCart = $this->entryActivate($request, $Customer->getSecretKey());
return $this->redirectToRoute('entry_activate', [
'secret_key' => $Customer->getSecretKey(),
'qtyInCart' => $qtyInCart,
]);
}
}
}
return [
'form' => $form->createView(),
'form_action' => $formAction,
'ref' => $ref,
];
}
/**
* 英語環境でのカナバリデーションエラーを除去
*/
private function removeKanaValidationErrorsForEnglish($form)
{
$locale = $this->session->get('_locale', 'ja');
if ($locale === 'en' && $form->isSubmitted()) {
// カナフィールドのエラーをクリア
if ($form->has('kana')) {
$kanaForm = $form->get('kana');
// フォームエラーをクリア
$this->clearFormErrors($kanaForm);
// 個別フィールドのエラーもクリア
if ($kanaForm->has('kana01')) {
$this->clearFormErrors($kanaForm->get('kana01'));
}
if ($kanaForm->has('kana02')) {
$this->clearFormErrors($kanaForm->get('kana02'));
}
}
}
}
/**
* フォームエラーをクリアする
*/
private function clearFormErrors($form)
{
// リフレクションを使ってプライベートなerrors配列をクリア
$reflection = new \ReflectionClass($form);
if ($reflection->hasProperty('errors')) {
$errorsProperty = $reflection->getProperty('errors');
$errorsProperty->setAccessible(true);
$errorsProperty->setValue($form, []);
}
}
/**
* 英語環境でのカナデータ処理
*/
private function handleEnglishKanaData($Customer)
{
$locale = $this->session->get('_locale', 'ja');
if ($locale === 'en') {
// カナフィールドを空文字または適切な値に設定
$Customer->setKana01(''); // 空文字
$Customer->setKana02(''); // 空文字
// または、名前をそのまま使用する場合:
$Customer->setKana01($Customer->getName01() ?: '');
$Customer->setKana02($Customer->getName02() ?: '');
}
}
/**
* 会員登録完了画面.
*
* @Route("/entry/complete", name="entry_complete", methods={"GET"})
* @Template("Entry/complete.twig")
*/
public function complete()
{
return [];
}
/**
* 会員のアクティベート(本会員化)を行う.
*
* @Route("/entry/activate/{secret_key}/{qtyInCart}", name="entry_activate", methods={"GET"})
* @Template("Entry/activate.twig")
*/
public function activate(Request $request, $secret_key, $qtyInCart = null)
{
$Customer = $this->customerRepository->getEmailChangeCustomerBySecretKey($secret_key);
//メールアドレス変更時の処理
if ($Customer) {
if ($Customer->getEmailChangeFlag() == 1) {
//変更前のメールアドレスを取得
$currentEmail = $Customer->getEmail();
//変更後のメールアドレスを取得
$changedEmail = $Customer->getChangeEmail();
//変更後のメールアドレスを保存
$Customer->setEmail($changedEmail);
//変更フラグをオフへ
$Customer->setEmailChangeFlag(0);
//変更後のメールアドレスをnullへ戻す
$Customer->setChangeEmail(null);
$this->entityManager->persist($Customer);
$this->entityManager->flush();
//変更完了のメール送信
$this->mailService->sendChangeMailCompleteMail($Customer, $currentEmail, $changedEmail);
return $this->redirectToRoute('complete_change_email');
}
}
$errors = $this->recursiveValidator->validate(
$secret_key,
[
new Assert\NotBlank(),
new Assert\Regex(
[
'pattern' => '/^[a-zA-Z0-9]+$/',
]
),
]
);
if (!$this->session->has('eccube.login.target.path')) {
$this->setLoginTargetPath($this->generateUrl('mypage', [], UrlGeneratorInterface::ABSOLUTE_URL));
}
if (!is_null($qtyInCart)) {
return [
'qtyInCart' => $qtyInCart,
];
} elseif ($request->getMethod() === 'GET' && count($errors) === 0) {
// 会員登録処理を行う
$qtyInCart = $this->entryActivate($request, $secret_key);
return [
'qtyInCart' => $qtyInCart,
];
}
throw new HttpException\NotFoundHttpException();
}
/**
* 会員登録処理を行う
*
* @param Request $request
* @param $secret_key
*
* @return \Eccube\Entity\Cart|mixed
*/
private function entryActivate(Request $request, $secret_key)
{
$Customer = $this->customerRepository->getProvisionalCustomerBySecretKey($secret_key);
if (!$Customer) {
$Customer = $this->customerRepository->getEmailChangeCustomerBySecretKey($secret_key);
}
//メールアドレス変更時の処理
if ($Customer->getEmailChangeFlag() == 1) {
$event = new EventArgs(
[
'Customer' => $Customer,
],
$request
);
$this->eventDispatcher->dispatch($event, EccubeEvents::FRONT_MYPAGE_CHANGE_INDEX_COMPLETE);
return $this->redirectToRoute('complete_change_email');
}
log_info('本会員登録開始');
if (is_null($Customer)) {
throw new HttpException\NotFoundHttpException();
}
$CustomerStatus = $this->customerStatusRepository->find(CustomerStatus::REGULAR);
$Customer->setStatus($CustomerStatus);
$this->entityManager->persist($Customer);
$this->entityManager->flush();
log_info('本会員登録完了');
$event = new EventArgs(
[
'Customer' => $Customer,
],
$request
);
$this->eventDispatcher->dispatch($event, EccubeEvents::FRONT_ENTRY_ACTIVATE_COMPLETE);
// メール送信
$this->mailService->sendCustomerCompleteMail($Customer);
// Assign session carts into customer carts
$Carts = $this->cartService->getCarts();
$qtyInCart = 0;
foreach ($Carts as $Cart) {
$qtyInCart += $Cart->getTotalQuantity();
}
if ($qtyInCart) {
$this->cartService->save();
}
return $qtyInCart;
}
}