<?php
namespace Plugin\FreeSample\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Routing\Annotation\Route;
use Eccube\Controller\AbstractController;
use Plugin\FreeSample\Form\Type\HistoryType;
use Plugin\FreeSample\Repository\HistoryRepository;
// use Eccube\Repository\ProductRepository;
use Plugin\FreeSample\Repository\ProductCustomRepository;
use Symfony\Component\HttpFoundation\Request;
// use Eccube\Service\MailService;
use Plugin\FreeSample\Service\FreeSampleMailService;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Plugin\FreeSample\Form\Type\HistoryRegisterType;
use Plugin\FreeSample\Entity\History;
use Plugin\FreeSample\Entity\HistoryProduct;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
class FreeSampleController extends AbstractController
{
protected $mailService;
protected $historyRepository;
protected $productRepository;
private $tokenStorage;
protected $authorizationChecker;
public function __construct(
FreeSampleMailService $mailService,
HistoryRepository $historyRepository,
ProductCustomRepository $productRepository,
TokenStorageInterface $tokenStorage,
AuthorizationCheckerInterface $authorizationChecker
) {
$this->mailService = $mailService;
$this->historyRepository = $historyRepository;
$this->productRepository = $productRepository;
$this->tokenStorage = $tokenStorage;
$this->authorizationChecker = $authorizationChecker;
}
/**
* @Route("/free_sample2", name="free_sample2_top",methods={"GET", "POST"})
* @Route("/free_sample2", name="free_sample2_top_confirm", methods={"GET", "POST"})
* @Template("free_sample2/index.twig")
*/
// @Template("@FreeSample/free_sample2/index.twig")
public function index(Request $request, SessionInterface $session)
{
$freeProducts = $session->get('free_products');
// 実際に存在する製品IDのみを保持するための新しい配列
$freeSampleProducts = [];
$historyProductsArray = [];
if (!empty($freeProducts)) {
foreach ($freeProducts as $index => $freeProduct) {
$product = $this->productRepository->findOneByIdAndStatus($freeProduct->getId(), 1);
if ($product) {
$freeSampleProducts[] = $product;
$historyProductsArray[] = [
"product_id" => $product,
];
}
}
$session->set('free_products', $freeSampleProducts);
}
if ($this->isGranted('ROLE_USER')) {
$user = $this->getUser();
$form = $this->createForm(HistoryRegisterType::class, [
'history' => [
'name01' => $user->getName01(),
'name02' => $user->getName02(),
'kana01' => $user->getKana01(),
'kana02' => $user->getKana02(),
'postal_code' => $user->getPostalCode(),
'pref' => $user->getPref(),
'addr01' => $user->getAddr01(),
'addr02' => $user->getAddr02(),
'phone_number' => $user->getPhoneNumber(),
'email' => $user->getEmail(),
],
'history_products' => $historyProductsArray
]);
} else {
$form = $this->createForm(HistoryRegisterType::class, [
'history_products' => $historyProductsArray
]);
}
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
if ("confirm" === $request->get('mode')) {
if (!count($freeSampleProducts)) {
$this->addFlash('free_sample2_error', 'サンプル製品は1件は必須です。');
return $this->redirect($this->generateUrl('free_sample2_top'));
}
// return $this->render('@FreeSample/free_sample2/confirm.twig', [
// 'form' => $form->createView(),
// 'products' => $freeSampleProducts
// ]);
return $this->render('free_sample2/confirm.twig', [
'form' => $form->createView(),
'products' => $freeSampleProducts
]);
} elseif ("complete" === $request->get('mode')) {
if (!count($freeSampleProducts)) {
$this->addFlash('free_sample2_error', 'サンプル製品は1件は必須です。');
return $this->redirect($this->generateUrl('free_sample2_top'));
}
if (!empty($session->get('free_complete_flag'))) {
//free_complete_flagがtrueならセッションを削除してリダイレクト
$session->remove('free_complete_flag');
return $this->redirect($this->generateUrl('free_sample2_top'));
}
$data = $form->getData();
$historyProductsPost = $data['history_products'];
$historyPost = $data["history"];
$this->entityManager->beginTransaction();
try {
$history = new History();
$history
->setCustomer($this->authorizationChecker->isGranted('ROLE_USER') ? $this->tokenStorage->getToken()->getUser() : null)
->setName01($historyPost['name01'])
->setName02($historyPost['name02'])
->setKana01(@$historyPost['kana01'])
->setKana02(@$historyPost['kana02'])
->setPostalCode(@$historyPost['postal_code'])
->setPref(@$historyPost['pref'])
->setAddr01(@$historyPost['addr01'])
->setAddr02(@$historyPost['addr02'])
->setPhoneNumber($historyPost['phone_number'])
->setEmail($historyPost['email'])
->setContents($historyPost['contents']);
$this->entityManager->persist($history);
$this->entityManager->flush();
foreach ($historyProductsPost as $index => $historyProductData) {
$historyProduct = new HistoryProduct();
//historyオブジェクトをセットする。
$historyProduct->setHistory($history)
->setProduct($historyProductData['product_id'])
->setName($historyProductData['product_id']->getName())
->setSortNo($index + 1);
$this->entityManager->persist($historyProduct);
}
$this->entityManager->flush();
$this->entityManager->commit();
} catch (\Exception $e) {
// トランザクションロールバック
$this->entityManager->rollback();
$this->addFlash('free_sample2_error', '処理中にエラーが発生しました。エラー:' . $e->getMessage());
return $this->redirect($this->generateUrl('free_sample2_complete'));
}
$this->mailService->sendFreeSampleMail($data);
$session->remove('free_products');
return $this->redirect($this->generateUrl('free_sample2_complete'));
}
}else{
if (!empty($session->get('free_complete_flag'))) {
$session->remove('free_complete_flag');
}
}
return [
'form' => $form->createView(),
'products' => $freeSampleProducts
];
}
/**
* 完了画面.
*
* @Route("/free_sample2/complete", name="free_sample2_complete", methods={"GET"})
* @Template("free_sample2/complete.twig")
*/
//@Template("@FreeSample/free_sample2/complete.twig")
public function complete(SessionInterface $session)
{
if (!empty($session->get('free_complete_flag'))) {
//free_complete_flagがtrueならセッションを削除してリダイレクト
$session->remove('free_complete_flag');
return $this->redirect($this->generateUrl('free_sample2_top'));
}
$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;
if ($referer) {
$path = parse_url($referer, PHP_URL_PATH);
if ($path == "/free_sample2" || $path == "free_sample2") {
$session->set('free_complete_flag', true);
}
}
return [];
}
/**
* @Route("/free_sample2/delete_sample/{id}", name="free_sample2_delete_sample",methods={"GET"},requirements={"id" = "\d+"})
*/
public function delete_sample(Request $request, SessionInterface $session, $id)
{
// セッションに保存されている製品IDの配列を取得
$freeProducts = $session->get('free_products', []);
// IDが一致しない要素だけを残してフィルタリング
$filteredProducts = array_filter($freeProducts, function ($product) use ($id) {
return $product->getId() != $id;
});
// フィルタリング前後で配列の長さが変わらなければ、製品は存在しない
if (count($filteredProducts) === count($freeProducts)) {
$this->addFlash('free_sample2_error', '削除する製品が存在しません');
return $this->redirect($this->generateUrl('free_sample2_top'));
}
// 更新された配列をセッションにセット
$session->set('free_products', $filteredProducts);
$this->addFlash('free_sample2_success', '製品が正常に削除されました');
return $this->redirect($this->generateUrl('free_sample2_top'));
}
/**
* @Route("/free_sample2/add_sample/{id}", name="free_sample2_add_sample",methods={"GET", "POST"},requirements={"id" = "\d+"})
*/
public function add_sample(Request $request, SessionInterface $session, $id)
{
$product = $this->productRepository->findOneByIdAndStatus($id, 1);
if (!$product) {
throw new NotFoundHttpException();
}
// セッションに保存されている製品IDの配列を取得
$freeProducts = $session->get('free_products', []);
$isNewProductExists = array_filter($freeProducts, function ($current) use ($product) {
return $current->getId() === $product->getId();
});
if (!empty($isNewProductExists)) {
// 製品IDが既に存在する場合、エラーメッセージをセッションに設定してリダイレクト
$this->addFlash('free_sample2_error', 'すでに追加されています。');
return $this->redirect($this->generateUrl('free_sample2_top'));
}
// 配列が5件以上の場合、エラーメッセージを設定してリダイレクト
if (count($freeProducts) >= 5) {
$session->set('free_sample2_error', 'すでに5件追加されています。');
return $this->redirect($this->generateUrl('free_sample2_top'));
}
$freeProducts[] = $product;
$session->set('free_products', $freeProducts);
return $this->redirect($this->generateUrl('free_sample2_top'));
}
}