app/Plugin/FreeSample/Controller/FreeSampleController.php line 231

Open in your IDE?
  1. <?php
  2. namespace Plugin\FreeSample\Controller;
  3. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  4. use Symfony\Component\Routing\Annotation\Route;
  5. use Eccube\Controller\AbstractController;
  6. use Plugin\FreeSample\Form\Type\HistoryType;
  7. use Plugin\FreeSample\Repository\HistoryRepository;
  8. // use Eccube\Repository\ProductRepository;
  9. use Plugin\FreeSample\Repository\ProductCustomRepository;
  10. use Symfony\Component\HttpFoundation\Request;
  11. // use Eccube\Service\MailService;
  12. use Plugin\FreeSample\Service\FreeSampleMailService;
  13. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  14. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  15. use Plugin\FreeSample\Form\Type\HistoryRegisterType;
  16. use Plugin\FreeSample\Entity\History;
  17. use Plugin\FreeSample\Entity\HistoryProduct;
  18. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  19. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  20. class FreeSampleController extends AbstractController
  21. {
  22.     protected $mailService;
  23.     protected $historyRepository;
  24.     protected $productRepository;
  25.     private $tokenStorage;
  26.     protected $authorizationChecker;
  27.     public function __construct(
  28.         FreeSampleMailService $mailService,
  29.         HistoryRepository $historyRepository,
  30.         ProductCustomRepository $productRepository,
  31.         TokenStorageInterface $tokenStorage,
  32.         AuthorizationCheckerInterface $authorizationChecker
  33.     ) {
  34.         $this->mailService $mailService;
  35.         $this->historyRepository $historyRepository;
  36.         $this->productRepository $productRepository;
  37.         $this->tokenStorage $tokenStorage;
  38.         $this->authorizationChecker $authorizationChecker;
  39.     }
  40.     /**
  41.      * @Route("/free_sample2", name="free_sample2_top",methods={"GET", "POST"})
  42.      * @Route("/free_sample2", name="free_sample2_top_confirm", methods={"GET", "POST"})
  43.      * @Template("free_sample2/index.twig")
  44.      */
  45.     //  @Template("@FreeSample/free_sample2/index.twig")
  46.     public function index(Request $requestSessionInterface $session)
  47.     {
  48.         $freeProducts $session->get('free_products');
  49.         // 実際に存在する製品IDのみを保持するための新しい配列
  50.         $freeSampleProducts = [];
  51.         $historyProductsArray = [];
  52.         if (!empty($freeProducts)) {
  53.             foreach ($freeProducts as $index => $freeProduct) {
  54.                 $product $this->productRepository->findOneByIdAndStatus($freeProduct->getId(), 1);
  55.                 if ($product) {
  56.                     $freeSampleProducts[] = $product;
  57.                     $historyProductsArray[] = [
  58.                         "product_id" => $product,
  59.                     ];
  60.                 }
  61.             }
  62.             $session->set('free_products'$freeSampleProducts);
  63.         }
  64.         if ($this->isGranted('ROLE_USER')) {
  65.             $user $this->getUser();
  66.             $form $this->createForm(HistoryRegisterType::class, [
  67.                 'history' => [
  68.                     'name01' => $user->getName01(),
  69.                     'name02' => $user->getName02(),
  70.                     'kana01' => $user->getKana01(),
  71.                     'kana02' => $user->getKana02(),
  72.                     'postal_code' => $user->getPostalCode(),
  73.                     'pref' => $user->getPref(),
  74.                     'addr01' => $user->getAddr01(),
  75.                     'addr02' => $user->getAddr02(),
  76.                     'phone_number' => $user->getPhoneNumber(),
  77.                     'email' => $user->getEmail(),
  78.                 ],
  79.                 'history_products' => $historyProductsArray
  80.             ]);
  81.         } else {
  82.             $form $this->createForm(HistoryRegisterType::class, [
  83.                 'history_products' => $historyProductsArray
  84.             ]);
  85.         }
  86.         $form->handleRequest($request);
  87.         if ($form->isSubmitted() && $form->isValid()) {
  88.             if ("confirm" === $request->get('mode')) {
  89.                 if (!count($freeSampleProducts)) {
  90.                     $this->addFlash('free_sample2_error''サンプル製品は1件は必須です。');
  91.                     return $this->redirect($this->generateUrl('free_sample2_top'));
  92.                 }
  93.                 // return $this->render('@FreeSample/free_sample2/confirm.twig', [
  94.                 //     'form' => $form->createView(),
  95.                 //     'products' => $freeSampleProducts
  96.                 // ]);
  97.                 return $this->render('free_sample2/confirm.twig', [
  98.                     'form' => $form->createView(),
  99.                     'products' => $freeSampleProducts
  100.                 ]);
  101.             } elseif ("complete" === $request->get('mode')) {
  102.                 if (!count($freeSampleProducts)) {
  103.                     $this->addFlash('free_sample2_error''サンプル製品は1件は必須です。');
  104.                     return $this->redirect($this->generateUrl('free_sample2_top'));
  105.                 }
  106.                 if (!empty($session->get('free_complete_flag'))) {
  107.                     //free_complete_flagがtrueならセッションを削除してリダイレクト
  108.                     $session->remove('free_complete_flag');
  109.                     return $this->redirect($this->generateUrl('free_sample2_top'));
  110.                 }
  111.               
  112.                 $data $form->getData();
  113.                 $historyProductsPost $data['history_products'];
  114.                 $historyPost $data["history"];
  115.                 $this->entityManager->beginTransaction();
  116.                 try {
  117.                     $history = new History();
  118.                     $history
  119.                         ->setCustomer($this->authorizationChecker->isGranted('ROLE_USER') ? $this->tokenStorage->getToken()->getUser() : null)
  120.                         ->setName01($historyPost['name01'])
  121.                         ->setName02($historyPost['name02'])
  122.                         ->setKana01(@$historyPost['kana01'])
  123.                         ->setKana02(@$historyPost['kana02'])
  124.                         ->setPostalCode(@$historyPost['postal_code'])
  125.                         ->setPref(@$historyPost['pref'])
  126.                         ->setAddr01(@$historyPost['addr01'])
  127.                         ->setAddr02(@$historyPost['addr02'])
  128.                         ->setPhoneNumber($historyPost['phone_number'])
  129.                         ->setEmail($historyPost['email'])
  130.                         ->setContents($historyPost['contents']);
  131.                     $this->entityManager->persist($history);
  132.                     $this->entityManager->flush();
  133.                     foreach ($historyProductsPost as $index => $historyProductData) {
  134.                         $historyProduct = new HistoryProduct();
  135.                         //historyオブジェクトをセットする。
  136.                         $historyProduct->setHistory($history)
  137.                             ->setProduct($historyProductData['product_id'])
  138.                             ->setName($historyProductData['product_id']->getName())
  139.                             ->setSortNo($index 1);
  140.                         $this->entityManager->persist($historyProduct);
  141.                     }
  142.                     $this->entityManager->flush();
  143.                     $this->entityManager->commit();
  144.                 } catch (\Exception $e) {
  145.                     // トランザクションロールバック
  146.                     $this->entityManager->rollback();
  147.                     $this->addFlash('free_sample2_error''処理中にエラーが発生しました。エラー:' $e->getMessage());
  148.                     return $this->redirect($this->generateUrl('free_sample2_complete'));
  149.                 }
  150.                 $this->mailService->sendFreeSampleMail($data);
  151.                 $session->remove('free_products');
  152.                 return $this->redirect($this->generateUrl('free_sample2_complete'));
  153.             }
  154.         }else{
  155.             if (!empty($session->get('free_complete_flag'))) {
  156.                 $session->remove('free_complete_flag');
  157.             }
  158.         }
  159.        
  160.         return [
  161.             'form' => $form->createView(),
  162.             'products' => $freeSampleProducts
  163.         ];
  164.     }
  165.     /**
  166.      * 完了画面.
  167.      *
  168.      * @Route("/free_sample2/complete", name="free_sample2_complete", methods={"GET"})
  169.      * @Template("free_sample2/complete.twig")
  170.      */
  171.      //@Template("@FreeSample/free_sample2/complete.twig")
  172.     public function complete(SessionInterface $session)
  173.     {
  174.         if (!empty($session->get('free_complete_flag'))) {
  175.             //free_complete_flagがtrueならセッションを削除してリダイレクト
  176.             $session->remove('free_complete_flag');
  177.             return $this->redirect($this->generateUrl('free_sample2_top'));
  178.         }
  179.         $referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;
  180.         if ($referer) {
  181.             $path parse_url($refererPHP_URL_PATH);
  182.             if ($path == "/free_sample2" || $path == "free_sample2") {
  183.                 $session->set('free_complete_flag'true);
  184.             }
  185.         }
  186.         return [];
  187.     }
  188.     /**
  189.      * @Route("/free_sample2/delete_sample/{id}", name="free_sample2_delete_sample",methods={"GET"},requirements={"id" = "\d+"})
  190.      */
  191.     public function delete_sample(Request $requestSessionInterface $session$id)
  192.     {
  193.         // セッションに保存されている製品IDの配列を取得
  194.         $freeProducts $session->get('free_products', []);
  195.         // IDが一致しない要素だけを残してフィルタリング
  196.         $filteredProducts array_filter($freeProducts, function ($product) use ($id) {
  197.             return $product->getId() != $id;
  198.         });
  199.         // フィルタリング前後で配列の長さが変わらなければ、製品は存在しない
  200.         if (count($filteredProducts) === count($freeProducts)) {
  201.             $this->addFlash('free_sample2_error''削除する製品が存在しません');
  202.             return $this->redirect($this->generateUrl('free_sample2_top'));
  203.         }
  204.         // 更新された配列をセッションにセット
  205.         $session->set('free_products'$filteredProducts);
  206.         $this->addFlash('free_sample2_success''製品が正常に削除されました');
  207.         return $this->redirect($this->generateUrl('free_sample2_top'));
  208.     }
  209.     /**
  210.      * @Route("/free_sample2/add_sample/{id}", name="free_sample2_add_sample",methods={"GET", "POST"},requirements={"id" = "\d+"})
  211.      */
  212.     public function add_sample(Request $requestSessionInterface $session$id)
  213.     {
  214.         $product $this->productRepository->findOneByIdAndStatus($id1);
  215.         if (!$product) {
  216.             throw new NotFoundHttpException();
  217.         }
  218.         // セッションに保存されている製品IDの配列を取得
  219.         $freeProducts $session->get('free_products', []);
  220.         $isNewProductExists array_filter($freeProducts, function ($current) use ($product) {
  221.             return $current->getId() === $product->getId();
  222.         });
  223.         if (!empty($isNewProductExists)) {
  224.             // 製品IDが既に存在する場合、エラーメッセージをセッションに設定してリダイレクト
  225.             $this->addFlash('free_sample2_error''すでに追加されています。');
  226.             return $this->redirect($this->generateUrl('free_sample2_top'));
  227.         }
  228.         // 配列が5件以上の場合、エラーメッセージを設定してリダイレクト
  229.         if (count($freeProducts) >= 5) {
  230.             $session->set('free_sample2_error''すでに5件追加されています。');
  231.             return $this->redirect($this->generateUrl('free_sample2_top'));
  232.         }
  233.         $freeProducts[] = $product;
  234.         $session->set('free_products'$freeProducts);
  235.         return $this->redirect($this->generateUrl('free_sample2_top'));
  236.     }
  237. }