app/Customize/Controller/ProductControllerExtends.php line 226

Open in your IDE?
  1. <?php
  2. namespace Customize\Controller;
  3. use Eccube\Controller\ProductController;
  4. use Eccube\Entity\BaseInfo;
  5. use Eccube\Entity\Product;
  6. use Eccube\Entity\Customer;
  7. use Eccube\Entity\Master\ProductStatus;
  8. use Eccube\Event\EccubeEvents;
  9. use Eccube\Event\EventArgs;
  10. use Eccube\Form\Type\AddCartType;
  11. use Eccube\Form\Type\SearchProductType;
  12. use Eccube\Repository\BaseInfoRepository;
  13. use Eccube\Repository\CustomerFavoriteProductRepository;
  14. use Eccube\Repository\Master\ProductListMaxRepository;
  15. use Customize\Repository\ProductRepository;
  16. use Customize\Repository\OrderRepository;
  17. use Eccube\Service\CartService;
  18. use Eccube\Service\PurchaseFlow\PurchaseContext;
  19. use Eccube\Service\PurchaseFlow\PurchaseFlow;
  20. use Knp\Bundle\PaginatorBundle\Pagination\SlidingPagination;
  21. use Knp\Component\Pager\PaginatorInterface;
  22. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  23. use Symfony\Component\HttpFoundation\Request;
  24. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  25. use Symfony\Component\Routing\Annotation\Route;
  26. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  27. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  28. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  29. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  30. use Doctrine\ORM\EntityManagerInterface;
  31. use Eccube\Entity\Order;
  32. class ProductControllerExtends extends ProductController
  33. {
  34.     /**
  35.      * @var PurchaseFlow
  36.      */
  37.     protected $purchaseFlow;
  38.     /**
  39.      * @var CustomerFavoriteProductRepository
  40.      */
  41.     protected $customerFavoriteProductRepository;
  42.     /**
  43.      * @var CartService
  44.      */
  45.     protected $cartService;
  46.     /**
  47.      * @var ProductRepository
  48.      */
  49.     protected $productRepository;
  50.     /**
  51.      * @var OrderRepository
  52.      */
  53.     protected $orderRepository;
  54.     /**
  55.      * @var BaseInfo
  56.      */
  57.     protected $BaseInfo;
  58.     /**
  59.      * @var AuthenticationUtils
  60.      */
  61.     protected $helper;
  62.     /**
  63.      * @var ProductListMaxRepository
  64.      */
  65.     protected $productListMaxRepository;
  66.     private $title '';
  67.     private EntityManagerInterface $em;
  68.     private TokenStorageInterface $tokenStorage;
  69.     /**
  70.      * ProductController constructor.
  71.      *
  72.      * @param PurchaseFlow $cartPurchaseFlow
  73.      * @param CustomerFavoriteProductRepository $customerFavoriteProductRepository
  74.      * @param CartService $cartService
  75.      * @param ProductRepository $productRepository
  76.      * @param OrderRepository $orderRepository
  77.      * @param BaseInfoRepository $baseInfoRepository
  78.      * @param AuthenticationUtils $helper
  79.      * @param ProductListMaxRepository $productListMaxRepository
  80.      */
  81.     public function __construct(
  82.         PurchaseFlow $cartPurchaseFlow,
  83.         CustomerFavoriteProductRepository $customerFavoriteProductRepository,
  84.         CartService $cartService,
  85.         ProductRepository $productRepository,
  86.         OrderRepository $orderRepository,
  87.         BaseInfoRepository $baseInfoRepository,
  88.         AuthenticationUtils $helper,
  89.         ProductListMaxRepository $productListMaxRepository,
  90.         EntityManagerInterface $em,
  91.         TokenStorageInterface $tokenStorage,
  92.     ) {
  93.         $this->purchaseFlow $cartPurchaseFlow;
  94.         $this->customerFavoriteProductRepository $customerFavoriteProductRepository;
  95.         $this->cartService $cartService;
  96.         $this->productRepository $productRepository;
  97.         $this->orderRepository $orderRepository;
  98.         $this->BaseInfo $baseInfoRepository->get();
  99.         $this->helper $helper;
  100.         $this->productListMaxRepository $productListMaxRepository;
  101.         $this->em $em;
  102.         $this->tokenStorage $tokenStorage;
  103.     }
  104.     /**
  105.      * 商品一覧画面.
  106.      *
  107.      * @Route("/products/list", name="product_list", methods={"GET"})
  108.      * @Template("Product/list.twig")
  109.      */
  110.     public function index(Request $requestPaginatorInterface $paginator)
  111.     {
  112.         // Doctrine SQLFilter
  113.         if ($this->BaseInfo->isOptionNostockHidden()) {
  114.             $this->entityManager->getFilters()->enable('option_nostock_hidden');
  115.         }
  116.         // handleRequestは空のqueryの場合は無視するため
  117.         if ($request->getMethod() === 'GET') {
  118.             $request->query->set('pageno'$request->query->get('pageno'''));
  119.         }
  120.         // searchForm
  121.         /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  122.         $builder $this->formFactory->createNamedBuilder(''SearchProductType::class);
  123.         if ($request->getMethod() === 'GET') {
  124.             $builder->setMethod('GET');
  125.         }
  126.         $event = new EventArgs(
  127.             [
  128.                 'builder' => $builder,
  129.             ],
  130.             $request
  131.         );
  132.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_INITIALIZE);
  133.         /* @var $searchForm \Symfony\Component\Form\FormInterface */
  134.         $searchForm $builder->getForm();
  135.         $searchForm->handleRequest($request);
  136.         // paginator
  137.         $searchData $searchForm->getData();
  138.         $qb $this->productRepository->getQueryBuilderBySearchData($searchData);
  139.         $event = new EventArgs(
  140.             [
  141.                 'searchData' => $searchData,
  142.                 'qb' => $qb,
  143.             ],
  144.             $request
  145.         );
  146.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_SEARCH);
  147.         $searchData $event->getArgument('searchData');
  148.         $query $qb->getQuery()
  149.             ->useResultCache(true$this->eccubeConfig['eccube_result_cache_lifetime_short']);
  150.         /** @var SlidingPagination $pagination */
  151.         $pagination $paginator->paginate(
  152.             $query,
  153.             !empty($searchData['pageno']) ? $searchData['pageno'] : 1,
  154.             !empty($searchData['disp_number']) ? $searchData['disp_number']->getId() : $this->productListMaxRepository->findOneBy([], ['sort_no' => 'ASC'])->getId()
  155.         );
  156.         $ids = [];
  157.         foreach ($pagination as $Product) {
  158.             $ids[] = $Product->getId();
  159.         }
  160.         $ProductsAndClassCategories $this->productRepository->findProductsWithSortedClassCategories($ids'p.id');
  161.         // addCart form
  162.         $forms = [];
  163.         foreach ($pagination as $Product) {
  164.             /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  165.             $builder $this->formFactory->createNamedBuilder(
  166.                 '',
  167.                 AddCartType::class,
  168.                 null,
  169.                 [
  170.                     'product' => $ProductsAndClassCategories[$Product->getId()],
  171.                     'allow_extra_fields' => true,
  172.                 ]
  173.             );
  174.             $addCartForm $builder->getForm();
  175.             $forms[$Product->getId()] = $addCartForm->createView();
  176.         }
  177.         $Category $searchForm->get('category_id')->getData();
  178.         return [
  179.             'subtitle' => $this->getPageTitle($searchData),
  180.             'pagination' => $pagination,
  181.             'search_form' => $searchForm->createView(),
  182.             'forms' => $forms,
  183.             'Category' => $Category,
  184.         ];
  185.     }
  186.     /**
  187.      * 商品詳細画面.
  188.      *
  189.      * @Route("/products/detail/{id}", name="product_detail", methods={"GET"}, requirements={"id" = "\d+"})
  190.      * @Template("Product/detail.twig")
  191.      * @ParamConverter("Product", options={"repository_method" = "findWithSortedClassCategories"})
  192.      *
  193.      * @param Request $request
  194.      * @param Product $Product
  195.      *
  196.      * @return array
  197.      */
  198.     public function detail(Request $requestProduct $Product)
  199.     {
  200.         if (!$this->checkVisibility($Product)) {
  201.             throw new NotFoundHttpException();
  202.         }
  203.         $builder $this->formFactory->createNamedBuilder(
  204.             '',
  205.             AddCartType::class,
  206.             null,
  207.             [
  208.                 'product' => $Product,
  209.                 'id_add_product_id' => false,
  210.             ]
  211.         );
  212.         $event = new EventArgs(
  213.             [
  214.                 'builder' => $builder,
  215.                 'Product' => $Product,
  216.             ],
  217.             $request
  218.         );
  219.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE);
  220.         $is_favorite false;
  221.         $has_purchased_recipe false// レシピ帖の商品を購入済み
  222.         $has_purchased_product false// 対象商品を購入済み
  223.         if ($this->isGranted('ROLE_USER')) {
  224.             $Customer $this->getUser();
  225.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  226.             $has_purchased_recipe $this->orderRepository->hasPurchasedRecipeProduct($Customer);
  227.             $has_purchased_product $this->orderRepository->hasPurchasedProduct($Customer$Product);
  228.             
  229.         }
  230.         
  231.         // レシピ帖の情報取得
  232.         $referencingProducts $this->productRepository->findProductsByRelatedRecipeProduct($Product);
  233.         return [
  234.             'title' => $this->title,
  235.             'subtitle' => $Product->getName(),
  236.             'form' => $builder->getForm()->createView(),
  237.             'Product' => $Product,
  238.             'is_favorite' => $is_favorite,
  239.             'has_purchased_recipe' => $has_purchased_recipe,
  240.             'has_purchased_product' => $has_purchased_product,
  241.             'referencingProducts' => $referencingProducts
  242.         ];
  243.     }
  244.     /**
  245.      * お気に入り追加.
  246.      *
  247.      * @Route("/products/add_favorite/{id}", name="product_add_favorite", requirements={"id" = "\d+"}, methods={"GET", "POST"})
  248.      */
  249.     public function addFavorite(Request $requestProduct $Product)
  250.     {
  251.         $this->checkVisibility($Product);
  252.         $event = new EventArgs(
  253.             [
  254.                 'Product' => $Product,
  255.             ],
  256.             $request
  257.         );
  258.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_INITIALIZE);
  259.         if ($this->isGranted('ROLE_USER')) {
  260.             $Customer $this->getUser();
  261.             $this->customerFavoriteProductRepository->addFavorite($Customer$Product);
  262.             $this->session->getFlashBag()->set('product_detail.just_added_favorite'$Product->getId());
  263.             $event = new EventArgs(
  264.                 [
  265.                     'Product' => $Product,
  266.                 ],
  267.                 $request
  268.             );
  269.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  270.             $referer $_SERVER['HTTP_REFERER'];
  271.             if (strpos($referer'cart') !== false) {
  272.                 return $this->redirectToRoute('cart'); 
  273.             } else {
  274.                 return $this->redirectToRoute('product_detail', ['id' => $Product->getId()]);
  275.             }
  276.         } else {
  277.             // 非会員の場合、ログイン画面を表示
  278.             //  ログイン後の画面遷移先を設定
  279.             $this->setLoginTargetPath($this->generateUrl('product_add_favorite', ['id' => $Product->getId()], UrlGeneratorInterface::ABSOLUTE_URL));
  280.             $this->session->getFlashBag()->set('eccube.add.favorite'true);
  281.             $event = new EventArgs(
  282.                 [
  283.                     'Product' => $Product,
  284.                 ],
  285.                 $request
  286.             );
  287.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  288.             return $this->redirectToRoute('mypage_login');
  289.         }
  290.     }
  291.     /**
  292.      * カートに追加.
  293.      *
  294.      * @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
  295.      */
  296.     public function addCart(Request $requestProduct $Product)
  297.     {
  298.         // エラーメッセージの配列
  299.         $errorMessages = [];
  300.         
  301.         if (!$this->checkVisibility($Product)) {
  302.             throw new NotFoundHttpException();
  303.         }
  304.         
  305.         $builder $this->formFactory->createNamedBuilder(
  306.             '',
  307.             AddCartType::class,
  308.             null,
  309.             [
  310.                 'product' => $Product,
  311.                 'id_add_product_id' => false,
  312.             ]
  313.         );
  314.         
  315.         $event = new EventArgs(
  316.             [
  317.                 'builder' => $builder,
  318.                 'Product' => $Product,
  319.             ],
  320.             $request
  321.         );
  322.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE);
  323.         
  324.         /* @var $form \Symfony\Component\Form\FormInterface */
  325.         $form $builder->getForm();
  326.         $form->handleRequest($request);
  327.         if (!$form->isValid()) {
  328.             throw new NotFoundHttpException();
  329.         }
  330.         $addCartData $form->getData();
  331.         
  332.         log_info(
  333.             'カート追加処理開始',
  334.             [
  335.                 'product_id' => $Product->getId(),
  336.                 'product_class_id' => $addCartData['product_class_id'],
  337.                 'quantity' => $addCartData['quantity'],
  338.             ]
  339.         );
  340.         // カートへ追加
  341.         $this->cartService->addProduct($addCartData['product_class_id'], $addCartData['quantity']);
  342.         // 明細の正規化
  343.         $Carts $this->cartService->getCarts();
  344.         $hasValidationError false;
  345.         foreach ($Carts as $Cart) {
  346.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  347.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  348.             if ($result->hasError()) {
  349.                 $hasValidationError true;
  350.                 try {
  351.                     $this->cartService->removeProduct($addCartData['product_class_id']);
  352.                 } catch (\Exception $e) {
  353.                     log_error("商品の削除に失敗しました", [
  354.                         'error' => $e->getMessage(),
  355.                         'product_class_id' => $addCartData['product_class_id']
  356.                     ]);
  357.                 }
  358.             
  359.                 foreach ($result->getErrors() as $error) {
  360.                     $errorMessages[] = $error->getMessage();
  361.                 }
  362.             }
  363.             foreach ($result->getWarning() as $warning) {
  364.                 $errorMessages[] = $warning->getMessage();
  365.             }
  366.         }
  367.         if (!$hasValidationError) {
  368.             $this->cartService->save();
  369.             log_info(
  370.                 'カート追加処理完了',
  371.                 [
  372.                     'product_id' => $Product->getId(),
  373.                     'product_class_id' => $addCartData['product_class_id'],
  374.                     'quantity' => $addCartData['quantity'],
  375.                 ]
  376.             );
  377.             // かご追加をSlackに通知する
  378.             $url 'https://hooks.slack.com/services/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';
  379.             
  380.             $message '';
  381.             if($this->isGranted('ROLE_USER')){
  382.                 $message "シコメルWebでカゴに商品が追加されました。\nユーザーID:".$this->getUser()->getId()."\n商品名:".$Product->getName();
  383.             } else {
  384.                 $message "シコメルWebでカゴに商品が追加されました。\n商品名:".$Product->getName();
  385.             }
  386.             $payload json_encode(['text' => $message]);
  387.             $ch curl_init($url);
  388.             curl_setopt($chCURLOPT_POSTtrue);
  389.             curl_setopt($chCURLOPT_POSTFIELDS$payload);
  390.             curl_setopt($chCURLOPT_HTTPHEADER, ['Content-Type: application/json']);
  391.             curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  392.             // Prod環境のみ実行
  393.             if (env('APP_ENV') == 'prod') {
  394.                 curl_exec($ch);
  395.             }
  396.             curl_close($ch);
  397.         }
  398.         $event = new EventArgs(
  399.             [
  400.                 'form' => $form,
  401.                 'Product' => $Product,
  402.             ],
  403.             $request
  404.         );
  405.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE);
  406.         if ($event->getResponse() !== null) {
  407.             return $event->getResponse();
  408.         }
  409.         if ($request->isXmlHttpRequest()) {
  410.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  411.             // 初期化
  412.             $messages = [];
  413.             if (empty($errorMessages)) {
  414.                 // エラーが発生していない場合
  415.                 $done true;
  416.                 array_push($messagestrans('front.product.add_cart_complete'));
  417.             } else {
  418.                 // エラーが発生している場合
  419.                 $done false;
  420.                 $messages $errorMessages;
  421.             }
  422.             return $this->json(['done' => $done'messages' => $messages]);
  423.         } else {
  424.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  425.             foreach ($errorMessages as $errorMessage) {
  426.                 $this->addRequestError($errorMessage);
  427.             }
  428.             return $this->redirectToRoute('cart');
  429.         }
  430.     }
  431.     /**
  432.      * ページタイトルの設定
  433.      *
  434.      * @param  array|null $searchData
  435.      *
  436.      * @return str
  437.      */
  438.     protected function getPageTitle($searchData)
  439.     {
  440.         if (isset($searchData['name']) && !empty($searchData['name'])) {
  441.             return "「" $searchData['name'] . "」に一致する" trans('front.product.search_result');
  442.         } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
  443.             return $searchData['category_id']->getName();
  444.         } else {
  445.             return trans('front.product.all_products');
  446.         }
  447.     }
  448.     /**
  449.      * 閲覧可能な商品かどうかを判定
  450.      *
  451.      * @param Product $Product
  452.      *
  453.      * @return boolean 閲覧可能な場合はtrue
  454.      */
  455.     protected function checkVisibility(Product $Product)
  456.     {
  457.         $is_admin $this->session->has('_security_admin');
  458.         // 管理ユーザの場合はステータスやオプションにかかわらず閲覧可能.
  459.         if (!$is_admin) {
  460.             // 在庫なし商品の非表示オプションが有効な場合.
  461.             // if ($this->BaseInfo->isOptionNostockHidden()) {
  462.             //     if (!$Product->getStockFind()) {
  463.             //         return false;
  464.             //     }
  465.             // }
  466.             // 公開ステータスでない商品は表示しない.
  467.             if ($Product->getStatus()->getId() !== ProductStatus::DISPLAY_SHOW) {
  468.                 return false;
  469.             }
  470.         }
  471.         return true;
  472.     }
  473. }