app/Plugin/SDream/Controller/ProductController.php line 143

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 Plugin\SDream\Controller;
  13. use Eccube\Entity\BaseInfo;
  14. use Eccube\Entity\Master\ProductStatus;
  15. use Eccube\Entity\Product;
  16. use Eccube\Event\EccubeEvents;
  17. use Eccube\Event\EventArgs;
  18. use Eccube\Form\Type\AddCartType;
  19. use Eccube\Form\Type\SearchProductType;
  20. use Eccube\Repository\BaseInfoRepository;
  21. use Eccube\Repository\CustomerFavoriteProductRepository;
  22. use Eccube\Repository\Master\ProductListMaxRepository;
  23. use Eccube\Repository\ProductRepository;
  24. use Eccube\Service\CartService;
  25. use Eccube\Service\PurchaseFlow\PurchaseContext;
  26. use Eccube\Service\PurchaseFlow\PurchaseFlow;
  27. use Knp\Bundle\PaginatorBundle\Pagination\SlidingPagination;
  28. use Knp\Component\Pager\PaginatorInterface;
  29. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  30. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  31. use Symfony\Component\HttpFoundation\Request;
  32. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  33. use Symfony\Component\Routing\Annotation\Route;
  34. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  35. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  36. use Eccube\Controller\AbstractController;
  37. use Plugin\SandreaOrinalPlugin\Repository\CategoryRepository;
  38. //ログをカスタマイズ出力
  39. //(/app/config/eccube/packages)
  40. //(W:\JOB\ECCUBE\colorful.dev\app\config\eccube\packages)
  41. //  app\config\eccube\packages\services.yaml
  42. //      monolog:channels: [''] ・・・ここに、ProductControllerを追加するだけ
  43. //      具体的には以下の通り
  44. //      channels: ['SDream', 'Paid4', 'SDreamShoppingController', 'SDreamCartController','SDreamAllowPaymentService','SandreaMailToSellerController','PriceCompareController','ProductController']  # 新しいチャンネルを追加
  45. class ProductController extends AbstractController
  46. {
  47.     const version 'ver.250206.001';
  48.     public function printConstant() {
  49.       return self::version;
  50.     }
  51.     /**
  52.      * @var PurchaseFlow
  53.      */
  54.     protected $purchaseFlow;
  55.     /**
  56.      * @var CustomerFavoriteProductRepository
  57.      */
  58.     protected $customerFavoriteProductRepository;
  59.     /**
  60.      * @var CartService
  61.      */
  62.     protected $cartService;
  63.     /**
  64.      * @var ProductRepository
  65.      */
  66.     protected $productRepository;
  67.     /**
  68.      * @var BaseInfo
  69.      */
  70.     protected $BaseInfo;
  71.     /**
  72.      * @var AuthenticationUtils
  73.      */
  74.     protected $helper;
  75.     /**
  76.      * @var ProductListMaxRepository
  77.      */
  78.     protected $productListMaxRepository;
  79.     private $title '';
  80.     /**
  81.      * @var HitemGuidListRepository
  82.      */
  83.     protected $hitemguidlistRepository;
  84.     /**
  85.      * @var CategoryRepository
  86.      */
  87.     protected $categoryRepository;
  88.     /**
  89.      * ProductController constructor.
  90.      *
  91.      * @param PurchaseFlow $cartPurchaseFlow
  92.      * @param CustomerFavoriteProductRepository $customerFavoriteProductRepository
  93.      * @param CartService $cartService
  94.      * @param ProductRepository $productRepository
  95.      * @param BaseInfoRepository $baseInfoRepository
  96.      * @param AuthenticationUtils $helper
  97.      * @param ProductListMaxRepository $productListMaxRepository
  98.      */
  99.     public function __construct(
  100.         PurchaseFlow $cartPurchaseFlow,
  101.         CustomerFavoriteProductRepository $customerFavoriteProductRepository,
  102.         CartService $cartService,
  103.         ProductRepository $productRepository,
  104.         BaseInfoRepository $baseInfoRepository,
  105.         AuthenticationUtils $helper,
  106.         ProductListMaxRepository $productListMaxRepository,
  107.         CategoryRepository $categoryRepository
  108.     ) {
  109.         $this->purchaseFlow $cartPurchaseFlow;
  110.         $this->customerFavoriteProductRepository $customerFavoriteProductRepository;
  111.         $this->cartService $cartService;
  112.         $this->productRepository $productRepository;
  113.         $this->BaseInfo $baseInfoRepository->get();
  114.         $this->helper $helper;
  115.         $this->productListMaxRepository $productListMaxRepository;
  116.         $this->categoryRepository $categoryRepository;
  117.     }
  118.     /**
  119.      * 商品一覧画面.
  120.      *
  121.      * @Route("/products/list", name="product_list", methods={"GET"})
  122.      * @Template("@SDream/Product/list.twig")
  123.      */
  124.     public function index(Request $requestPaginatorInterface $paginator)
  125.     {
  126.         // Doctrine SQLFilter
  127.         if ($this->BaseInfo->isOptionNostockHidden()) {
  128.             $this->entityManager->getFilters()->enable('option_nostock_hidden');
  129.         }
  130.         // handleRequestは空のqueryの場合は無視するため
  131.         if ($request->getMethod() === 'GET') {
  132.             $request->query->set('pageno'$request->query->get('pageno'''));
  133.         }
  134.         //limited_ids調査 25.2
  135.         $customer $this->getUser(); // 現在のログインユーザーを取得
  136.         $customerId $customer $customer->getId() : null;
  137.         // searchForm
  138.         /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  139.         $builder $this->formFactory->createNamedBuilder(''SearchProductType::class);
  140.         if ($request->getMethod() === 'GET') {
  141.             $builder->setMethod('GET');
  142.         }
  143.         $event = new EventArgs(
  144.             [
  145.                 'builder' => $builder,
  146.             ],
  147.             $request
  148.         );
  149.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_INITIALIZE);
  150.         /* @var $searchForm \Symfony\Component\Form\FormInterface */
  151.         $searchForm $builder->getForm();
  152.         $searchForm->handleRequest($request);
  153.         // paginator
  154.         $searchData $searchForm->getData();
  155.         $qb $this->productRepository->getQueryBuilderBySearchData($searchData);
  156.         //limited_ids調査 25.2
  157.         // SQL を確認 (limited_ids の影響調査) ・・・ 結果影響なし ここでは正しく抽出できている。
  158.         //logs('ProductController')->info('getQueryBuilderBySearchData(A001000)'.$qb->getDQL());
  159.         //logs('ProductController')->info('getQueryBuilderBySearchData(A002000)'.$qb->getQuery()->getSQL());
  160.         $event = new EventArgs(
  161.             [
  162.                 'searchData' => $searchData,
  163.                 'qb' => $qb,
  164.             ],
  165.             $request
  166.         );
  167.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_SEARCH);
  168.         $searchData $event->getArgument('searchData');
  169.         $query $qb->getQuery()
  170.             ->useResultCache(true$this->eccubeConfig['eccube_result_cache_lifetime_short']);
  171.         /** @var SlidingPagination $pagination */
  172.         $pagination $paginator->paginate(
  173.             $query,
  174.             !empty($searchData['pageno']) ? $searchData['pageno'] : 1,
  175.             !empty($searchData['disp_number']) ? $searchData['disp_number']->getId() : $this->productListMaxRepository->findOneBy([], ['sort_no' => 'ASC'])->getId()
  176.         );
  177.         //limited_ids調査 25.2
  178.         //// $pagination の段階で limited_ids による除外がされているか を確認 (limited_ids の影響調査) ・・・ 
  179.         //dump($pagination->getItems());
  180.         //exit;
  181.         //表示限定顧客
  182.         //$limited_ids = $Product->getLimitedIds();
  183.         $ids = [];
  184.         foreach ($pagination as $Product) {
  185.             $ids[] = $Product->getId();
  186.         }
  187.         $ProductsAndClassCategories $this->productRepository->findProductsWithSortedClassCategories($ids'p.id');
  188.         // addCart form
  189.         $forms = [];
  190.         foreach ($pagination as $Product) {
  191.             /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  192.             $builder $this->formFactory->createNamedBuilder(
  193.                 '',
  194.                 AddCartType::class,
  195.                 null,
  196.                 [
  197.                     'product' => $ProductsAndClassCategories[$Product->getId()],
  198.                     'allow_extra_fields' => true,
  199.                 ]
  200.             );
  201.             $addCartForm $builder->getForm();
  202.             $forms[$Product->getId()] = $addCartForm->createView();
  203.         }
  204.         $Category $searchForm->get('category_id')->getData();
  205.         /* カテゴリごとのメタ情報を取得する */
  206.         $categoryId null;
  207.         $SeoMetaTitle null;
  208.         $SeoMetaKeywords null;
  209.         $SeoMetaDescription null;
  210.         $CategoryPicfilename null;
  211.         if ($Category) {
  212.             $SeoMetaTitle$Category->getSeoMetaTitle();
  213.             $SeoMetaKeywords$Category->getSeoMetaKeywords();
  214.             $SeoMetaDescription$Category->getSeoMetaDescription();
  215.             $CategoryPicfilename$Category->getCategoryPicfilename();
  216.             $categoryId =$searchForm->get('category_id')->getData();
  217.         }
  218.         /* カテゴリに割当られて「 商品リスト 」を取得 */
  219.         $category21products = [];
  220.         $categoryList=[];
  221.         $categorySelf="";
  222.         if ($categoryId) {
  223.             // サブクエリの構築
  224.             $subQb =  $this->categoryRepository->createQueryBuilder('sub')
  225.                 ->select('sub.id')
  226.                 ->where('sub.Parent = :subParentCategory');
  227.             // クエリビルダーを使用してデータを取得
  228.             $qb $this->categoryRepository->createQueryBuilder('c')
  229.             ->select('c.id as category_id''c.name as category_name''pc.product_id''p.name as product_name''IDENTITY(c.Parent) as parent_category_id''parent.sort_no as parent_sort_no')
  230.             ->join('c.ProductCategories''pc')
  231.             ->join('pc.Product''p')
  232.             ->join('p.Status''s')
  233.             ->leftJoin('c.Parent''parent')
  234.             ->where($qb->expr()->in('c.Parent'$subQb->getDQL()))// サブクエリを条件に追加
  235.             ->andWhere('c.id != :excludedCategory')
  236.             ->andWhere('s.id = :productStatus')// ステータスIDでフィルタリング
  237.             ->orderBy('parent.sort_no''DESC')// sc.sort_no の降順にソート
  238.             ->addOrderBy('c.sort_no''DESC')// c.sort_no の降順にソート
  239.             ->setParameter('subParentCategory'11)//21と同じ階層であるが、意味合い的には21の配下にしたいそうだ。
  240.             ->setParameter('excludedCategory'21)//21は除外する
  241.             ->setParameter('productStatus'1);// 表示ステータスのみ
  242.             $query $qb->getQuery();
  243.             $products $query->getArrayResult();
  244.             /**
  245.              * 
  246.              * 【税 以降をカット
  247.              * 
  248.              */
  249.             $category21products array_map(function($product) {
  250.                 $product['product_name'] = explode('【税'$product['product_name'])[0];
  251.                 return $product;
  252.             }, $products);
  253.             
  254.             $categoryList $this->categoryRepository->getCategoryHierarchy($categoryId);
  255.             $categorySelf=$this->categoryRepository->getCategorySelf($categoryId);
  256.             //echo '<pre>';
  257.             //print_r($categorySelf);
  258.             //echo '</pre>';
  259.             //var_dump($categorySelf);
  260.         }
  261.         return [
  262.             'subtitle' => $this->getPageTitle($searchData),
  263.             'pagination' => $pagination,
  264.             'search_form' => $searchForm->createView(),
  265.             'forms' => $forms,
  266.             'Category' => $Category,
  267.             'SeoMetaTitle' => $SeoMetaTitle,
  268.             'SeoMetaKeywords' => $SeoMetaKeywords,
  269.             'SeoMetaDescription' => $SeoMetaDescription,
  270.             'CategoryPicfilename' => $CategoryPicfilename,
  271.             'Category21Products' => $category21products,
  272.             'CategorySelf' => $categorySelf,
  273.             'CategoryList' => $categoryList,
  274.             'current_customer_id' => $customerId// Twig に渡す
  275.         ];
  276.     }
  277.     /**
  278.      * 商品詳細画面.
  279.      *
  280.      * @Route("/products/detail/{id}", name="product_detail", methods={"GET"}, requirements={"id" = "\d+"})
  281.      * @Template("@SDream/Product/detail.twig")
  282.      * @ParamConverter("Product", options={"repository_method" = "findWithSortedClassCategories"})
  283.      * 
  284.      *
  285.      * @param Request $request
  286.      * @param Product $Product
  287.      *
  288.      * @return array
  289.      */
  290.     public function detail(Request $requestProduct $Product)
  291.     {
  292.         if (!$this->checkVisibility($Product)) {
  293.             throw new NotFoundHttpException();
  294.         }
  295.         $builder $this->formFactory->createNamedBuilder(
  296.             '',
  297.             AddCartType::class,
  298.             null,
  299.             [
  300.                 'product' => $Product,
  301.                 'id_add_product_id' => false,
  302.             ]
  303.         );
  304.         $event = new EventArgs(
  305.             [
  306.                 'builder' => $builder,
  307.                 'Product' => $Product,
  308.             ],
  309.             $request
  310.         );
  311.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE);
  312.         
  313.         $is_favorite false;
  314.         $userId '';
  315.         if ($this->isGranted('ROLE_USER')) {
  316.             $Customer $this->getUser();
  317.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  318.             $userId $Customer $Customer->getId() : null;
  319.         }
  320.         
  321.         
  322.         //表示限定顧客
  323.         $limited_ids $Product->getLimitedIds();
  324.         $host $_SERVER['HTTP_HOST'];
  325.         if($limited_ids != '') {
  326.             $limited_ids explode(','$Product->getLimitedIds());
  327.             if ($userId && in_array($userId$limited_ids)) {
  328.             //    echo "$userId は含まれています";
  329.             //     このエコーを入れると「Warning: Cannot modify header information - headers already sent by (output started at /home/izamrldn/public_html/dev.sandrea.jp/src/Eccube/Controller/ProductController.php:265)」が発生する
  330.             } else {
  331.                 //お気に入りへ飛ばす
  332.                 return $this->redirect('https://' $host '/mypage/favorite'301);
  333.             }
  334.         }
  335.         //非表示限定顧客
  336.         $locked_ids $Product->getLockedIds();
  337.         if($locked_ids != '') {
  338.             if($userId == null){
  339.                 return $this->redirect('https://' $host301);  
  340.             }
  341.             $locked_ids explode(','$Product->getLockedIds());
  342.             if ($userId && in_array($userId$locked_ids)) {
  343.                 //表示させたくないので、TOPへ飛ばす
  344.                 return $this->redirect('https://' $host301);  
  345.             }
  346.         } 
  347.         return [
  348.             'title' => $this->title,
  349.             'subtitle' => $Product->getName(),
  350.             'form' => $builder->getForm()->createView(),
  351.             'Product' => $Product,
  352.             'is_favorite' => $is_favorite,
  353.         ];
  354.     }
  355.     /**
  356.      * お気に入り追加.
  357.      *
  358.      * @Route("/products/add_favorite/{id}", name="product_add_favorite", requirements={"id" = "\d+"}, methods={"GET", "POST"})
  359.      */
  360.     public function addFavorite(Request $requestProduct $Product)
  361.     {
  362.         $this->checkVisibility($Product);
  363.         $event = new EventArgs(
  364.             [
  365.                 'Product' => $Product,
  366.             ],
  367.             $request
  368.         );
  369.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_INITIALIZE);
  370.         if ($this->isGranted('ROLE_USER')) {
  371.             $Customer $this->getUser();
  372.             $this->customerFavoriteProductRepository->addFavorite($Customer$Product);
  373.             $this->session->getFlashBag()->set('product_detail.just_added_favorite'$Product->getId());
  374.             $event = new EventArgs(
  375.                 [
  376.                     'Product' => $Product,
  377.                 ],
  378.                 $request
  379.             );
  380.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  381.             return $this->redirectToRoute('product_detail', ['id' => $Product->getId()]);
  382.         } else {
  383.             // 非会員の場合、ログイン画面を表示
  384.             //  ログイン後の画面遷移先を設定
  385.             $this->setLoginTargetPath($this->generateUrl('product_add_favorite', ['id' => $Product->getId()], UrlGeneratorInterface::ABSOLUTE_URL));
  386.             $this->session->getFlashBag()->set('eccube.add.favorite'true);
  387.             $event = new EventArgs(
  388.                 [
  389.                     'Product' => $Product,
  390.                 ],
  391.                 $request
  392.             );
  393.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  394.             return $this->redirectToRoute('mypage_login');
  395.         }
  396.     }
  397.     /**
  398.      * カートに追加.
  399.      *
  400.      * @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
  401.      */
  402.     public function addCart(Request $requestProduct $Product)
  403.     {
  404.         // エラーメッセージの配列
  405.         $errorMessages = [];
  406.         if (!$this->checkVisibility($Product)) {
  407.             throw new NotFoundHttpException();
  408.         }
  409.         $builder $this->formFactory->createNamedBuilder(
  410.             '',
  411.             AddCartType::class,
  412.             null,
  413.             [
  414.                 'product' => $Product,
  415.                 'id_add_product_id' => false,
  416.             ]
  417.         );
  418.         $event = new EventArgs(
  419.             [
  420.                 'builder' => $builder,
  421.                 'Product' => $Product,
  422.             ],
  423.             $request
  424.         );
  425.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE);
  426.         /* @var $form \Symfony\Component\Form\FormInterface */
  427.         $form $builder->getForm();
  428.         $form->handleRequest($request);
  429.         if (!$form->isValid()) {
  430.             throw new NotFoundHttpException();
  431.         }
  432.         $addCartData $form->getData();
  433.         log_info(
  434.             'カート追加処理開始',
  435.             [
  436.                 'product_id' => $Product->getId(),
  437.                 'product_class_id' => $addCartData['product_class_id'],
  438.                 'quantity' => $addCartData['quantity'],
  439.             ]
  440.         );
  441.         // カートへ追加
  442.         $this->cartService->addProduct($addCartData['product_class_id'], $addCartData['quantity']);
  443.         // 明細の正規化
  444.         $Carts $this->cartService->getCarts();
  445.         foreach ($Carts as $Cart) {
  446.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  447.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  448.             if ($result->hasError()) {
  449.                 $this->cartService->removeProduct($addCartData['product_class_id']);
  450.                 foreach ($result->getErrors() as $error) {
  451.                     $errorMessages[] = $error->getMessage();
  452.                 }
  453.             }
  454.             foreach ($result->getWarning() as $warning) {
  455.                 $errorMessages[] = $warning->getMessage();
  456.             }
  457.         }
  458.         $this->cartService->save();
  459.         log_info(
  460.             'カート追加処理完了',
  461.             [
  462.                 'product_id' => $Product->getId(),
  463.                 'product_class_id' => $addCartData['product_class_id'],
  464.                 'quantity' => $addCartData['quantity'],
  465.             ]
  466.         );
  467.         $event = new EventArgs(
  468.             [
  469.                 'form' => $form,
  470.                 'Product' => $Product,
  471.             ],
  472.             $request
  473.         );
  474.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE);
  475.         if ($event->getResponse() !== null) {
  476.             return $event->getResponse();
  477.         }
  478.         if ($request->isXmlHttpRequest()) {
  479.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  480.             // 初期化
  481.             $messages = [];
  482.             if (empty($errorMessages)) {
  483.                 // エラーが発生していない場合
  484.                 $done true;
  485.                 array_push($messagestrans('front.product.add_cart_complete'));
  486.             } else {
  487.                 // エラーが発生している場合
  488.                 $done false;
  489.                 $messages $errorMessages;
  490.             }
  491.             return $this->json(['done' => $done'messages' => $messages]);
  492.         } else {
  493.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  494.             foreach ($errorMessages as $errorMessage) {
  495.                 $this->addRequestError($errorMessage);
  496.             }
  497.             return $this->redirectToRoute('cart');
  498.         }
  499.     }
  500.     /**
  501.      * ページタイトルの設定
  502.      *
  503.      * @param  array|null $searchData
  504.      *
  505.      * @return str
  506.      */
  507.     protected function getPageTitle($searchData)
  508.     {
  509.         if (isset($searchData['name']) && !empty($searchData['name'])) {
  510.             return trans('front.product.search_result');
  511.         } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
  512.             return $searchData['category_id']->getName();
  513.         } else {
  514.             return trans('front.product.all_products');
  515.         }
  516.     }
  517.     /**
  518.      * 閲覧可能な商品かどうかを判定
  519.      *
  520.      * @param Product $Product
  521.      *
  522.      * @return boolean 閲覧可能な場合はtrue
  523.      */
  524.     protected function checkVisibility(Product $Product)
  525.     {
  526.         $is_admin $this->session->has('_security_admin');
  527.         // 管理ユーザの場合はステータスやオプションにかかわらず閲覧可能.
  528.         if (!$is_admin) {
  529.             // 在庫なし商品の非表示オプションが有効な場合.
  530.             // if ($this->BaseInfo->isOptionNostockHidden()) {
  531.             //     if (!$Product->getStockFind()) {
  532.             //         return false;
  533.             //     }
  534.             // }
  535.             // 公開ステータスでない商品は表示しない.
  536.             if ($Product->getStatus()->getId() !== ProductStatus::DISPLAY_SHOW) {
  537.                 return false;
  538.             }
  539.         }
  540.         return true;
  541.     }
  542. }