app/Customize/Controller/ProductControllerCustomizer.php line 92

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of EC-CUBE
  4.  *
  5.  * Copyright(c) EC-CUBE CO.,LTD. All Rights Reserved.
  6.  *
  7.  * http://www.ec-cube.co.jp/
  8.  *
  9.  * For the full copyright and license information, please view the LICENSE
  10.  * file that was distributed with this source code.
  11.  */
  12. namespace Customize\Controller;
  13. use Eccube\Entity\BaseInfo;
  14. use Eccube\Entity\Master\ProductStatus;
  15. use Eccube\Entity\Product;
  16. use Eccube\Entity\Order;
  17. use Eccube\Entity\OrderItem;
  18. use Eccube\Entity\ProductClass;
  19. use Eccube\Event\EccubeEvents;
  20. use Eccube\Event\EventArgs;
  21. use Eccube\Form\Type\AddCartType;
  22. use Eccube\Form\Type\SearchProductType;
  23. use Eccube\Repository\BaseInfoRepository;
  24. use Eccube\Repository\CustomerFavoriteProductRepository;
  25. use Eccube\Repository\Master\ProductListMaxRepository;
  26. use Eccube\Repository\ProductRepository;
  27. use Eccube\Repository\OrderRepository;
  28. use Eccube\Service\CartService;
  29. use Eccube\Service\PurchaseFlow\PurchaseContext;
  30. use Eccube\Service\PurchaseFlow\PurchaseFlow;
  31. use Knp\Bundle\PaginatorBundle\Pagination\SlidingPagination;
  32. use Knp\Component\Pager\PaginatorInterface;
  33. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  34. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  35. use Symfony\Component\HttpFoundation\Request;
  36. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  37. use Symfony\Component\Routing\Annotation\Route;
  38. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  39. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  40. use Eccube\Controller\ProductController;
  41. class ProductControllerCustomizer extends ProductController
  42. {
  43.     /**
  44.      * @var OrderRepository
  45.      */
  46.     protected $orderRepository;
  47.     /**
  48.      * ProductController constructor.
  49.      *
  50.      * @param PurchaseFlow $cartPurchaseFlow
  51.      * @param CustomerFavoriteProductRepository $customerFavoriteProductRepository
  52.      * @param CartService $cartService
  53.      * @param ProductRepository $productRepository
  54.      * @param BaseInfoRepository $baseInfoRepository
  55.      * @param AuthenticationUtils $helper
  56.      * @param ProductListMaxRepository $productListMaxRepository
  57.      * @param OrderRepository $orderRepository
  58.      */
  59.     public function __construct(
  60.         PurchaseFlow $cartPurchaseFlow,
  61.         CustomerFavoriteProductRepository $customerFavoriteProductRepository,
  62.         CartService $cartService,
  63.         ProductRepository $productRepository,
  64.         BaseInfoRepository $baseInfoRepository,
  65.         AuthenticationUtils $helper,
  66.         ProductListMaxRepository $productListMaxRepository,
  67.         OrderRepository $orderRepository
  68.     ) {
  69.         parent::__construct($cartPurchaseFlow,
  70.           $customerFavoriteProductRepository,
  71.           $cartService,
  72.           $productRepository,
  73.           $baseInfoRepository,
  74.           $helper,
  75.           $productListMaxRepository
  76.         );
  77.         $this->orderRepository $orderRepository;
  78.     }
  79.     
  80.     /**
  81.      * 商品一覧画面.
  82.      *
  83.      * @Route("/products/list", name="product_list", methods={"GET"})
  84.      * @Template("Product/list.twig")
  85.      */
  86.     public function index(Request $requestPaginatorInterface $paginator)
  87.     {
  88.         // Doctrine SQLFilter
  89.         if ($this->BaseInfo->isOptionNostockHidden()) {
  90.             $this->entityManager->getFilters()->enable('option_nostock_hidden');
  91.         }
  92.         // handleRequestは空のqueryの場合は無視するため
  93.         if ($request->getMethod() === 'GET') {
  94.             $request->query->set('pageno'$request->query->get('pageno'''));
  95.         }
  96.         // searchForm
  97.         /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  98.         $builder $this->formFactory->createNamedBuilder(''SearchProductType::class);
  99.         if ($request->getMethod() === 'GET') {
  100.             $builder->setMethod('GET');
  101.         }
  102.         $event = new EventArgs(
  103.             [
  104.                 'builder' => $builder,
  105.             ],
  106.             $request
  107.         );
  108.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_INITIALIZE);
  109.         /* @var $searchForm \Symfony\Component\Form\FormInterface */
  110.         $searchForm $builder->getForm();
  111.         $searchForm->handleRequest($request);
  112.         // paginator
  113.         $searchData $searchForm->getData();
  114.         $qb $this->productRepository->getQueryBuilderBySearchData($searchData);
  115.         $event = new EventArgs(
  116.             [
  117.                 'searchData' => $searchData,
  118.                 'qb' => $qb,
  119.             ],
  120.             $request
  121.         );
  122.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_SEARCH);
  123.         $searchData $event->getArgument('searchData');
  124.         $query $qb->getQuery()
  125.             ->useResultCache(true$this->eccubeConfig['eccube_result_cache_lifetime_short']);
  126.         /*$qb = $this->entityManager->getRepository('Eccube\Entity\Product')
  127.         ->createQueryBuilder('p');
  128.         $qb->innerJoin('p.ProductTag', 'pt')
  129.         ->innerJoin('pt.Tag', 't')
  130.         ->andWhere('t = :Tag')
  131.         ->setParameter('Tag', 17);*/
  132.         
  133.         $query $qb->getQuery()->getResult();
  134.         
  135.         /** @var SlidingPagination $pagination */
  136.         $pagination $paginator->paginate(
  137.             $query,
  138.             !empty($searchData['pageno']) ? $searchData['pageno'] : 1,
  139.             200
  140.         );
  141.         $Category $searchForm->get('category_id')->getData();
  142.         /*
  143.         // ▼ボツの追加処理ここから
  144.         $is_admin = $this->session->has('_security_admin');
  145.         $period = '';
  146.         $Carts = $this->cartService->getCarts();
  147.         foreach ($Carts as $Cart) {
  148.             foreach ($Cart->getItems() as $item) {
  149.                 $period = $item->getPeriod();
  150.             }
  151.         }
  152.         // 受注情報から、予約済みレンタル期間を取得 ←削除
  153.         $arrReserved = [];
  154.         $arrOrder = $this->orderRepository->findAll();
  155.         foreach ($pagination as $Product) {
  156.           $arrPeriod = [];
  157.           $product_id = $Product->getId();
  158.           foreach ($arrOrder as $order) {
  159.             if ($order->getOrderStatus() != '購入処理中' && $order->getOrderStatus() != '注文取消し') {
  160.               foreach ($order->getItems() as $item) {
  161.                 $class = $item->getProductClass();
  162.                 if ($class) {
  163.                   if ($class->getProduct()->getId() == $product_id) {
  164.                     $val = $item->getPeriod();
  165.                     if ($val) {
  166.                       $arrPeriod[] = $val;
  167.                     }
  168.                   }
  169.                 }
  170.               }
  171.             }
  172.           }
  173.           // 商品情報から、貸出不可期間を取得
  174.           $invalidity_period = $Product->getInvalidityPeriod();
  175.           if ($invalidity_period) {
  176.             $arrPeriod[] = $invalidity_period;
  177.           }
  178.           $arrReserved[] = implode(';', $arrPeriod);
  179.         }
  180.         // ▲ボツの追加処理ここまで */
  181.         
  182.         // 追加処理ここから
  183.         foreach ($pagination as $Product) {
  184.           if ($this->isGranted('ROLE_USER')) {
  185.               $Customer $this->getUser();
  186.               $Product->setSearchWord($this->customerFavoriteProductRepository->isFavorite($Customer$Product));
  187.           }
  188.           else {
  189.               $Product->setSearchWord('');
  190.           }
  191.         }
  192.         // 追加処理ここまで
  193.         return [
  194.             'subtitle' => $this->getPageTitle($searchData),
  195.             'pagination' => $pagination,
  196.             'search_form' => $searchForm->createView(),
  197.             //'forms' => $forms,
  198.             'Category' => $Category,
  199.             // ▼以下、追加
  200.             //'is_admin' => $is_admin,
  201.             //'period' => $period,
  202.             //'reserved' => implode('|', $arrReserved),
  203.         ];
  204.     }
  205.     /**
  206.      * 商品詳細画面.
  207.      *
  208.      * @Route("/products/detail/{id}", name="product_detail", methods={"GET"}, requirements={"id" = "\d+"})
  209.      * @Template("Product/detail.twig")
  210.      * @ParamConverter("Product", options={"repository_method" = "findWithSortedClassCategories"})
  211.      *
  212.      * @param Request $request
  213.      * @param Product $Product
  214.      *
  215.      * @return array
  216.      */
  217.     public function detail(Request $requestProduct $Product)
  218.     {
  219.         if (!$this->checkVisibility($Product)) {
  220.             throw new NotFoundHttpException();
  221.         }
  222.         $builder $this->formFactory->createNamedBuilder(
  223.             '',
  224.             AddCartType::class,
  225.             null,
  226.             [
  227.                 'product' => $Product,
  228.                 'id_add_product_id' => false,
  229.             ]
  230.         );
  231.         $event = new EventArgs(
  232.             [
  233.                 'builder' => $builder,
  234.                 'Product' => $Product,
  235.             ],
  236.             $request
  237.         );
  238.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE);
  239.         $is_favorite false;
  240.         if ($this->isGranted('ROLE_USER')) {
  241.             $Customer $this->getUser();
  242.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  243.         }
  244.         // ▼追加処理ここから
  245.         $is_admin $this->session->has('_security_admin');
  246.         $sale_type '';
  247.         foreach ($Product->getProductClasses() as $ProductClass) {
  248.             $val $ProductClass->getSaleType()->getId();
  249.             if ($val == || $val == 4) {
  250.               $sale_type 3;
  251.             }
  252.         }
  253.         $period '';
  254.         $Carts $this->cartService->getCarts();
  255.         foreach ($Carts as $Cart) {
  256.             foreach ($Cart->getItems() as $item) {
  257.                 $period $item->getPeriod();
  258.             }
  259.         }
  260.         // 受注情報から、予約済みレンタル期間を取得
  261.         $arrPeriod = [];
  262.         foreach ($this->orderRepository->findAll() as $order) {
  263.           if ($order->getOrderStatus() != '購入処理中' && $order->getOrderStatus() != '注文取消し') {
  264.             foreach ($order->getItems() as $item) {
  265.               $class $item->getProductClass();
  266.               if ($class) {
  267.                 //echo $order->getId();
  268.                 if ($class->getProduct()->getId() == $Product->getId()) {
  269.                   $val $item->getPeriod();
  270.                   if ($val) {
  271.                     $vals explode('|'$val);
  272.                     $arrPeriod[] = $vals[0];
  273.                   }
  274.                 }
  275.               }
  276.             }
  277.           }
  278.         }
  279.         // 商品情報から、貸出不可期間を取得
  280.         $invalidity_period $Product->getInvalidityPeriod();
  281.         if ($invalidity_period) {
  282.           $arrPeriod[] = $invalidity_period;
  283.         }
  284.         $user_status 0;
  285.         if ($this->isGranted('ROLE_USER')) {
  286.           $user_status $this->getUser()->getStatus()->getId();
  287.         }
  288.         // ▲追加処理ここまで
  289.         //var_dump($_SERVER['RENTAL_SETTING']);
  290.         return [
  291.             'title' => '',
  292.             'subtitle' => $Product->getName(),
  293.             'form' => $builder->getForm()->createView(),
  294.             'Product' => $Product,
  295.             'is_favorite' => $is_favorite,
  296.             // ▼以下、追加
  297.             'is_admin' => $is_admin,
  298.             'sale_type' => $sale_type,
  299.             'period' => $period,
  300.             'reserved' => implode(';'$arrPeriod),
  301.             'user_status' => $user_status,
  302.             'rental_setting' => $_SERVER['RENTAL_SETTING'],
  303.         ];
  304.     }
  305.     /**
  306.      * カートに追加.
  307.      *
  308.      * @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
  309.      */
  310.     public function addCart(Request $requestProduct $Product)
  311.     {
  312.         // エラーメッセージの配列
  313.         $errorMessages = [];
  314.         if (!$this->checkVisibility($Product)) {
  315.             throw new NotFoundHttpException();
  316.         }
  317.         $builder $this->formFactory->createNamedBuilder(
  318.             '',
  319.             AddCartType::class,
  320.             null,
  321.             [
  322.                 'product' => $Product,
  323.                 'id_add_product_id' => false,
  324.             ]
  325.         );
  326.         $event = new EventArgs(
  327.             [
  328.                 'builder' => $builder,
  329.                 'Product' => $Product,
  330.             ],
  331.             $request
  332.         );
  333.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE);
  334.         /* @var $form \Symfony\Component\Form\FormInterface */
  335.         $form $builder->getForm();
  336.         $form->handleRequest($request);
  337.         if (!$form->isValid()) {
  338.             throw new NotFoundHttpException();
  339.         }
  340.         $addCartData $form->getData();
  341.         log_info(
  342.             'カート追加処理開始',
  343.             [
  344.                 'product_id' => $Product->getId(),
  345.                 'product_class_id' => $addCartData['product_class_id'],
  346.                 'quantity' => $addCartData['quantity'],
  347.                 'period' => $addCartData['period'], // ▲コード追加
  348.             ]
  349.         );
  350.         // カートへ追加
  351.         // ▼変更処理ここから
  352.         //$this->cartService->addProduct($addCartData['product_class_id'], $addCartData['quantity']);
  353.         $this->cartService->addCartItem($addCartData['product_class_id'], $addCartData['quantity'], [
  354.             'period' => $addCartData['period'],
  355.         ]);
  356.         // ▲変更処理ここまで
  357.         // 明細の正規化
  358.         $Carts $this->cartService->getCarts();
  359.         foreach ($Carts as $Cart) {
  360.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  361.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  362.             if ($result->hasError()) {
  363.                 $this->cartService->removeProduct($addCartData['product_class_id']);
  364.                 foreach ($result->getErrors() as $error) {
  365.                     $errorMessages[] = $error->getMessage();
  366.                 }
  367.             }
  368.             foreach ($result->getWarning() as $warning) {
  369.                 $errorMessages[] = $warning->getMessage();
  370.             }
  371.         }
  372.         $this->cartService->save();
  373.         log_info(
  374.             'カート追加処理完了',
  375.             [
  376.                 'product_id' => $Product->getId(),
  377.                 'product_class_id' => $addCartData['product_class_id'],
  378.                 'quantity' => $addCartData['quantity'],
  379.             ]
  380.         );
  381.         $event = new EventArgs(
  382.             [
  383.                 'form' => $form,
  384.                 'Product' => $Product,
  385.             ],
  386.             $request
  387.         );
  388.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE);
  389.         if ($event->getResponse() !== null) {
  390.             return $event->getResponse();
  391.         }
  392.         if ($request->isXmlHttpRequest()) {
  393.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  394.             // 初期化
  395.             $messages = [];
  396.             if (empty($errorMessages)) {
  397.                 // エラーが発生していない場合
  398.                 $done true;
  399.                 array_push($messagestrans('front.product.add_cart_complete'));
  400.             } else {
  401.                 // エラーが発生している場合
  402.                 $done false;
  403.                 $messages $errorMessages;
  404.             }
  405.             return $this->json(['done' => $done'messages' => $messages]);
  406.         } else {
  407.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  408.             foreach ($errorMessages as $errorMessage) {
  409.                 $this->addRequestError($errorMessage);
  410.             }
  411.             return $this->redirectToRoute('cart');
  412.         }
  413.     }
  414. }