app/Customize/Controller/ProductController.php line 293

Open in your IDE?
  1. <?php
  2. namespace Customize\Controller;
  3. use Customize\Repository\OrderDetailAdditionalInfoRepository;
  4. use Eccube\Entity\Product;
  5. use Eccube\Entity\BaseInfo;
  6. use Eccube\Event\EventArgs;
  7. use Eccube\Event\EccubeEvents;
  8. use Eccube\Service\CartService;
  9. use Eccube\Form\Type\AddCartType;
  10. use Eccube\Entity\ProductCategory;
  11. use Eccube\Entity\Master\ProductStatus;
  12. use Eccube\Form\Type\SearchProductType;
  13. use Eccube\Controller\AbstractController;
  14. use Eccube\Repository\BaseInfoRepository;
  15. use Customize\Repository\ProductRepository;
  16. use Knp\Component\Pager\PaginatorInterface;
  17. use Eccube\Service\PurchaseFlow\PurchaseFlow;
  18. use Symfony\Component\HttpFoundation\Request;
  19. use Eccube\Form\Type\Master\ProductListMaxType;
  20. use Symfony\Component\Routing\Annotation\Route;
  21. use Eccube\Service\PurchaseFlow\PurchaseContext;
  22. use Eccube\Form\Type\Master\ProductListOrderByType;
  23. use Eccube\Repository\Master\ProductListMaxRepository;
  24. use Eccube\Repository\CustomerFavoriteProductRepository;
  25. use Knp\Bundle\PaginatorBundle\Pagination\SlidingPagination;
  26. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  27. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  28. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  29. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  30. use Plugin\PlgExpandProductColumns\Entity\PlgExpandProductColumnsValue;
  31. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  32. use Customize\Common\Constants;
  33. use Customize\Entity\ProductDescription;
  34. use Eccube\Common\EccubeConfig;
  35. class ProductController extends AbstractController
  36. {
  37.     /**
  38.      * @var PurchaseFlow
  39.      */
  40.     protected $purchaseFlow;
  41.     /**
  42.      * @var CustomerFavoriteProductRepository
  43.      */
  44.     protected $customerFavoriteProductRepository;
  45.     /**
  46.      * @var CartService
  47.      */
  48.     protected $cartService;
  49.     /**
  50.      * @var ProductRepository
  51.      */
  52.     protected $productRepository;
  53.     /**
  54.      * @var BaseInfo
  55.      */
  56.     protected $BaseInfo;
  57.     /**
  58.      * @var AuthenticationUtils
  59.      */
  60.     protected $helper;
  61.     /**
  62.      * @var ProductListMaxRepository
  63.      */
  64.     protected $productListMaxRepository;
  65.     private $title '';
  66.     private $orderDetailAdditionalInfoRepository;
  67.     /**
  68.      * ProductController constructor.
  69.      *
  70.      * @param PurchaseFlow $cartPurchaseFlow
  71.      * @param CustomerFavoriteProductRepository $customerFavoriteProductRepository
  72.      * @param CartService $cartService
  73.      * @param ProductRepository $productRepository
  74.      * @param BaseInfoRepository $baseInfoRepository
  75.      * @param AuthenticationUtils $helper
  76.      * @param ProductListMaxRepository $productListMaxRepository
  77.      */
  78.     public function __construct(
  79.         PurchaseFlow $cartPurchaseFlow,
  80.         CustomerFavoriteProductRepository $customerFavoriteProductRepository,
  81.         CartService $cartService,
  82.         ProductRepository $productRepository,
  83.         BaseInfoRepository $baseInfoRepository,
  84.         AuthenticationUtils $helper,
  85.         ProductListMaxRepository $productListMaxRepository,
  86.         OrderDetailAdditionalInfoRepository $orderDetailAdditionalInfoRepository,
  87.         EccubeConfig $eccubeConfig,
  88.     ) {
  89.         $this->purchaseFlow $cartPurchaseFlow;
  90.         $this->customerFavoriteProductRepository $customerFavoriteProductRepository;
  91.         $this->cartService $cartService;
  92.         $this->productRepository $productRepository;
  93.         $this->BaseInfo $baseInfoRepository->get();
  94.         $this->helper $helper;
  95.         $this->productListMaxRepository $productListMaxRepository;
  96.         $this->orderDetailAdditionalInfoRepository $orderDetailAdditionalInfoRepository;
  97.         $this->eccubeConfig $eccubeConfig;
  98.     }
  99.     /**
  100.      * 商品一覧画面.
  101.      *
  102.      * @Route("/products/list", name="product_list", methods={"GET"})
  103.      * @Template("Product/list.twig")
  104.      */
  105.     public function index(Request $requestPaginatorInterface $paginator)
  106.     {
  107.         // Doctrine SQLFilter
  108.         if ($this->BaseInfo->isOptionNostockHidden()) {
  109.             $this->entityManager->getFilters()->enable('option_nostock_hidden');
  110.         }
  111.         // handleRequestは空のqueryの場合は無視するため
  112.         if ($request->getMethod() === 'GET') {
  113.             $request->query->set('pageno'$request->query->get('pageno'''));
  114.         }
  115.         // searchForm
  116.         /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  117.         $builder $this->formFactory->createNamedBuilder(''SearchProductType::class);
  118.         if ($request->getMethod() === 'GET') {
  119.             $builder->setMethod('GET');
  120.         }
  121.         $event = new EventArgs(
  122.             [
  123.                 'builder' => $builder,
  124.             ],
  125.             $request
  126.         );
  127.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_INITIALIZE);
  128.         /* @var $searchForm \Symfony\Component\Form\FormInterface */
  129.         $searchForm $builder->getForm();
  130.         $searchForm->handleRequest($request);
  131.         // paginator
  132.         $searchData $searchForm->getData();
  133.         // Get list category custom
  134.         $categories = [];
  135.         for ($i 0$i <= 4$i++) {
  136.             $paramName 'category_id_' $i;
  137.             if ($request->query->has($paramName)) {
  138.                 $categories[] = $request->query->get($paramName);
  139.             }
  140.         }
  141.         $date $request->query->get('date');
  142.         $qb $this->productRepository->getQueryBuilderBySearchData($searchData$this->entityManager$categories$date);
  143.         $event = new EventArgs(
  144.             [
  145.                 'searchData' => $searchData,
  146.                 'qb' => $qb,
  147.             ],
  148.             $request
  149.         );
  150.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_SEARCH);
  151.         $searchData $event->getArgument('searchData');
  152.         $query $qb->getQuery()
  153.             ->useResultCache(true$this->eccubeConfig['eccube_result_cache_lifetime_short']);
  154.         /** @var SlidingPagination $pagination */
  155.         $pagination $paginator->paginate(
  156.             $query,
  157.             !empty($searchData['pageno']) ? $searchData['pageno'] : 1,
  158.             !empty($searchData['disp_number']) ? $searchData['disp_number']->getId() : $this->productListMaxRepository->findOneBy([], ['sort_no' => 'ASC'])->getId()
  159.         );
  160.         // Choice number product to show page
  161.         $dispNumberForm $this->formFactory->createNamed('disp_number'ProductListMaxType::class, null, [
  162.             'method' => 'GET',
  163.             'empty_data' => null,
  164.             'required' => false,
  165.             'label' => '表示件数',
  166.             'allow_extra_fields' => true,
  167.         ])->handleRequest($request);
  168.         $ids = [];
  169.         foreach ($pagination as $Product) {
  170.             $ids[] = $Product->getId();
  171.         }
  172.         $ProductsAndClassCategories $this->productRepository->findProductsWithSortedClassCategories($ids'p.id');
  173.         // Order by form
  174.         $orderByForm $this->formFactory->createNamed('orderby'ProductListOrderByType::class, null, [
  175.             'method' => 'GET',
  176.             'empty_data' => null,
  177.             'required' => false,
  178.             'label' => '表示件数',
  179.             'allow_extra_fields' => true,
  180.         ])->handleRequest($request);
  181.         // addCart form
  182.         $forms = [];
  183.         foreach ($pagination as $Product) {
  184.             if (!isset($ProductsAndClassCategories[$Product->getId()])) {
  185.                 continue;
  186.             }
  187.             /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  188.             $builder $this->formFactory->createNamedBuilder(
  189.                 '',
  190.                 AddCartType::class,
  191.                 null,
  192.                 [
  193.                     'product' => $ProductsAndClassCategories[$Product->getId()],
  194.                     'allow_extra_fields' => true,
  195.                 ]
  196.             );
  197.             $addCartForm $builder->getForm();
  198.             $forms[$Product->getId()] = $addCartForm->createView();
  199.         }
  200.         $Category $searchForm->get('category_id')->getData();
  201.         return [
  202.             'subtitle' => $this->getPageTitle($searchData),
  203.             'pagination' => $pagination,
  204.             'search_form' => $searchForm->createView(),
  205.             'forms' => $forms,
  206.             'Category' => $Category,
  207.             'disp_number_form' => $dispNumberForm->createView(),
  208.             'order_by_form' => $orderByForm->createView(),
  209.         ];
  210.     }
  211. /**
  212.      * 商品詳細画面.
  213.      *
  214.      * @Route("/products/discontinued", name="products_discontinued", methods={"GET"})
  215.      * @Template("Product/discontinued.twig")
  216.      *
  217.      * @param Request $request
  218.      * @return array
  219.      */
  220.     public function discontinued (Request $request){}
  221.     /**
  222.      * 商品詳細画面.
  223.      *
  224.      * @Route("/products/detail/{id}", name="product_detail", methods={"GET"}, requirements={"id" = "\d+"})
  225.      * @Template("Product/detail.twig")
  226.      * @ParamConverter("Product", options={"repository_method" = "findWithSortedClassCategories"})
  227.      *
  228.      * @param Request $request
  229.      * @param Product $Product
  230.      *
  231.      * @return array
  232.      */
  233.     public function detail(Request $requestProduct $Product)
  234.     {
  235.         $result $this->validateLocale($request$Product);
  236.         // if product language is different from locale url
  237.         if ($result['isPass'] == false) {
  238.             return $this->redirectToRoute('product_detail_locale', [
  239.                 'id' => $Product->getId(),
  240.                 '_locale' => $result['locale']
  241.             ]);
  242.         }
  243.         if (!$this->checkVisibility($Product)) {
  244.             return $this->redirectToRoute('products_discontinued');
  245.         }
  246.         if ($_SERVER['SERVER_NAME'] === env("SALON_URL")) {
  247.             $notShowTMV $this->entityManager->getRepository(ProductCategory::class)->createQueryBuilder('p')
  248.                 ->where('p.product_id = :product_id and p.category_id in (' $this->eccubeConfig['category_not_show_tmv'] . ')')
  249.                 ->setParameter('product_id'$Product->getId())
  250.                 ->getQuery()
  251.                 ->getResult();
  252.             if ($notShowTMV) {
  253.                 throw new NotFoundHttpException();
  254.             }
  255.         }
  256.         $builder $this->formFactory->createNamedBuilder(
  257.             '',
  258.             AddCartType::class,
  259.             null,
  260.             [
  261.                 'product' => $Product,
  262.                 'id_add_product_id' => false,
  263.             ]
  264.         );
  265.         $event = new EventArgs(
  266.             [
  267.                 'builder' => $builder,
  268.                 'Product' => $Product,
  269.             ],
  270.             $request
  271.         );
  272.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE);
  273.         $is_favorite false;
  274.         if ($this->isGranted('ROLE_USER')) {
  275.             $Customer $this->getUser();
  276.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  277.         }
  278.         $productNotAvailableDates = [];
  279.         if ($_SERVER['SERVER_NAME'] === env("SALON_URL")) {
  280.             $productNotAvailableDates = [
  281.                 'normal'  => $this->orderDetailAdditionalInfoRepository->getListNotAvailableDates($this->entityManager$Product->getId()),
  282.                 'fitting'  => $this->orderDetailAdditionalInfoRepository->getListNotAvailableDates($this->entityManager$Product->getId(), 'fitting'),
  283.                 'flex'  => $this->orderDetailAdditionalInfoRepository->getListNotAvailableDates($this->entityManager$Product->getId(), 'flex')
  284.             ];
  285.             $startDetail strpos($Product->getDescriptionDetail(), '<div');
  286.             if ($startDetail !== false) {
  287.                 $Product->setDescriptionDetail(substr($Product->getDescriptionDetail(), 0$startDetail));
  288.             }
  289.         }
  290.         $productDescription $this->entityManager->getRepository(ProductDescription::class)->findOneBy([
  291.             'product_id' => $Product->getId(),
  292.         ]);
  293.         return [
  294.             'title' => $this->title,
  295.             'subtitle' => $Product->getName(),
  296.             'form' => $builder->getForm()->createView(),
  297.             'Product' => $Product,
  298.             'is_favorite' => $is_favorite,
  299.             'productNotAvailableDates' => json_encode($productNotAvailableDates),
  300.             'productDescription' => $productDescription
  301.         ];
  302.     }
  303.     /**
  304.      * 商品詳細画面.
  305.      *
  306.      * @Route("/{_locale}/products/detail/{id}", name="product_detail_locale", methods={"GET"}, requirements={"id" = "\d+"})
  307.      * @Template("Product/detail.twig")
  308.      * @ParamConverter("Product", options={"repository_method" = "findWithSortedClassCategories"})
  309.      *
  310.      * @param Request $request
  311.      * @param Product $Product
  312.      *
  313.      * @return array
  314.      */
  315.     public function detailLocale(Request $requestProduct $Product)
  316.     {
  317.         if ($this->eccubeConfig['salon_domain'] == $_SERVER['SERVER_NAME']) {
  318.             return $this->redirectToRoute('homepage');
  319.         }
  320.         $result $this->validateLocale($request$Product);
  321.         // if product language is different from locale url
  322.         if ($result['isPass'] == false) {
  323.             return $this->redirectToRoute('product_detail_locale', [
  324.                 'id' => $Product->getId(),
  325.                 '_locale' => $result['locale']
  326.             ]);
  327.         }
  328.         if ($request->getLocale() == Constants::LOCALE_JAPAN) {
  329.             return $this->redirectToRoute('product_detail', [
  330.                 'id' => $Product->getId(),
  331.             ]);
  332.         }
  333.         return $this->detail($request$Product);
  334.     }
  335.     /**
  336.      * お気に入り追加.
  337.      *
  338.      * @Route("/products/add_favorite/{id}", name="product_add_favorite", requirements={"id" = "\d+"}, methods={"GET", "POST"})
  339.      */
  340.     public function addFavorite(Request $requestProduct $Product)
  341.     {
  342.         $this->checkVisibility($Product);
  343.         $event = new EventArgs(
  344.             [
  345.                 'Product' => $Product,
  346.             ],
  347.             $request
  348.         );
  349.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_INITIALIZE);
  350.         if ($this->isGranted('ROLE_USER')) {
  351.             $Customer $this->getUser();
  352.             $this->customerFavoriteProductRepository->addFavorite($Customer$Product);
  353.             $this->session->getFlashBag()->set('product_detail.just_added_favorite'$Product->getId());
  354.             $event = new EventArgs(
  355.                 [
  356.                     'Product' => $Product,
  357.                 ],
  358.                 $request
  359.             );
  360.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  361.             return $this->redirectToRoute('product_detail', ['id' => $Product->getId()]);
  362.         } else {
  363.             // 非会員の場合、ログイン画面を表示
  364.             //  ログイン後の画面遷移先を設定
  365.             $this->setLoginTargetPath($this->generateUrl('product_add_favorite', ['id' => $Product->getId()], UrlGeneratorInterface::ABSOLUTE_URL));
  366.             $this->session->getFlashBag()->set('eccube.add.favorite'true);
  367.             $event = new EventArgs(
  368.                 [
  369.                     'Product' => $Product,
  370.                 ],
  371.                 $request
  372.             );
  373.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  374.             return $this->redirectToRoute('mypage_login');
  375.         }
  376.     }
  377.     /**
  378.      * カートに追加.
  379.      *
  380.      * @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
  381.      */
  382.     public function addCart(Request $requestProduct $Product)
  383.     {
  384.         // エラーメッセージの配列
  385.         $errorMessages = [];
  386.         if (!$this->checkVisibility($Product)) {
  387.             throw new NotFoundHttpException();
  388.         }
  389.         $builder $this->formFactory->createNamedBuilder(
  390.             '',
  391.             AddCartType::class,
  392.             null,
  393.             [
  394.                 'product' => $Product,
  395.                 'id_add_product_id' => false,
  396.                 'allow_extra_fields' => true,
  397.             ]
  398.         );
  399.         $event = new EventArgs(
  400.             [
  401.                 'builder' => $builder,
  402.                 'Product' => $Product,
  403.             ],
  404.             $request
  405.         );
  406.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE);
  407.         /* @var $form \Symfony\Component\Form\FormInterface */
  408.         $form $builder->getForm();
  409.         $form->handleRequest($request);
  410.         if (!$form->isValid()) {
  411.             throw new NotFoundHttpException();
  412.         }
  413.         $addCartData $form->getData();
  414.         log_info(
  415.             'カート追加処理開始',
  416.             [
  417.                 'product_id' => $Product->getId(),
  418.                 'product_class_id' => $addCartData['product_class_id'],
  419.                 'quantity' => $addCartData['quantity'],
  420.             ]
  421.         );
  422.         // カートへ追加
  423.         $this->cartService->addProductOverride($addCartData['product_class_id'], $addCartData['quantity'], $form);
  424.         // 明細の正規化
  425.         $Carts $this->cartService->getCarts();
  426.         foreach ($Carts as $Cart) {
  427.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  428.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  429.             if ($result->hasError()) {
  430.                 $this->cartService->removeProduct($addCartData['product_class_id']);
  431.                 foreach ($result->getErrors() as $error) {
  432.                     $errorMessages[] = $error->getMessage();
  433.                 }
  434.             }
  435.             foreach ($result->getWarning() as $warning) {
  436.                 $errorMessages[] = $warning->getMessage();
  437.             }
  438.         }
  439.         $this->cartService->save();
  440.         log_info(
  441.             'カート追加処理完了',
  442.             [
  443.                 'product_id' => $Product->getId(),
  444.                 'product_class_id' => $addCartData['product_class_id'],
  445.                 'quantity' => $addCartData['quantity'],
  446.             ]
  447.         );
  448.         $event = new EventArgs(
  449.             [
  450.                 'form' => $form,
  451.                 'Product' => $Product,
  452.             ],
  453.             $request
  454.         );
  455.         if (empty($errorMessages)) {
  456.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE);
  457.         }
  458.         if ($event->getResponse() !== null) {
  459.             return $event->getResponse();
  460.         }
  461.         if ($request->isXmlHttpRequest()) {
  462.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  463.             // 初期化
  464.             $messages = [];
  465.             if (empty($errorMessages)) {
  466.                 // エラーが発生していない場合
  467.                 $done true;
  468.                 array_push($messagestrans('front.product.add_cart_complete'));
  469.             } else {
  470.                 // エラーが発生している場合
  471.                 $done false;
  472.                 $messages $errorMessages;
  473.             }
  474.             return $this->json(['done' => $done'messages' => $messages]);
  475.         } else {
  476.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  477.             foreach ($errorMessages as $errorMessage) {
  478.                 $this->addRequestError($errorMessage);
  479.             }
  480.             if ($request->get('_locale') != Constants::LOCALE_JAPAN && $request->get('_locale') != null) {
  481.                 return $this->redirectToRoute('cart_locale');
  482.             }
  483.             return $this->redirectToRoute('cart');
  484.         }
  485.     }
  486.     /**
  487.      * カートに追加.
  488.      *
  489.      * @Route("/{_locale}/products/add_cart/{id}", name="product_add_cart_locale", methods={"POST"}, requirements={"id" = "\d+"})
  490.      */
  491.     public function addCartLocale(Request $requestProduct $Product)
  492.     {
  493.         return $this->addCart($request$Product);
  494.     }
  495.     /**
  496.      * ページタイトルの設定
  497.      *
  498.      * @param  array|null $searchData
  499.      *
  500.      * @return str
  501.      */
  502.     protected function getPageTitle($searchData)
  503.     {
  504.         if (isset($searchData['name']) && !empty($searchData['name'])) {
  505.             return trans('front.product.search_result');
  506.         } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
  507.             return $searchData['category_id']->getName();
  508.         } else {
  509.             return trans('front.product.all_products');
  510.         }
  511.     }
  512.     /**
  513.      * 閲覧可能な商品かどうかを判定
  514.      *
  515.      * @param Product $Product
  516.      *
  517.      * @return boolean 閲覧可能な場合はtrue
  518.      */
  519.     protected function checkVisibility(Product $Product)
  520.     {
  521.         $is_admin $this->session->has('_security_admin');
  522.         // 管理ユーザの場合はステータスやオプションにかかわらず閲覧可能.
  523.         if (!$is_admin) {
  524.             if ($Product->getStatus()->getId() !== ProductStatus::DISPLAY_SHOW) {
  525.                 return false;
  526.             }
  527.         }
  528.         return true;
  529.     }
  530.     //check if product language is same with url locale
  531.     public function validateLocale(Request $requestProduct $product)
  532.     {
  533.         // get locale from user request
  534.         $localeUrl $request->getLocale();
  535.         try {
  536.             // find record in database
  537.             $result $this->entityManager->getRepository(PlgExpandProductColumnsValue::class)->findOneBy([
  538.                 'productId' => $product->getId(),
  539.                 'columnId' => Constants::LOCALE_RECORD_ID
  540.             ]);
  541.             $localeSetting = empty($result) ? Constants::LOCALE_JAPAN $result->getValue();
  542.         } catch (\Exception $ex) {
  543.             log_info('Error when get value working with plg_expand_product_columns_value table');
  544.             $localeSetting Constants::LOCALE_JAPAN;
  545.         }
  546.         // if product locale not same with url access
  547.         $isPass $localeUrl == $localeSetting;
  548.         return [
  549.             'isPass' => $isPass,
  550.             'locale' => $localeSetting
  551.         ];
  552.     }
  553. }