app/Customize/Controller/ProductController.php line 724

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\ProductClass;
  17. use Eccube\Event\EccubeEvents;
  18. use Eccube\Event\EventArgs;
  19. use Customize\Form\Type\AddCartType;
  20. use Customize\Form\Type\SearchProductType;
  21. use Eccube\Repository\BaseInfoRepository;
  22. use Eccube\Repository\CustomerFavoriteProductRepository;
  23. use Eccube\Repository\Master\ProductListMaxRepository;
  24. use Customize\Repository\ProductRepository;
  25. use Eccube\Controller\AbstractController;
  26. use Eccube\Service\CartService;
  27. use Eccube\Service\PurchaseFlow\PurchaseContext;
  28. use Eccube\Service\PurchaseFlow\PurchaseFlow;
  29. use Knp\Bundle\PaginatorBundle\Pagination\SlidingPagination;
  30. use Knp\Component\Pager\PaginatorInterface;
  31. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  32. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  33. use Symfony\Component\HttpFoundation\Request;
  34. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  35. use Symfony\Component\Routing\Annotation\Route;
  36. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  37. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  38. use Plugin\ProductField\Repository\ConfigRepository;
  39. class ProductController extends AbstractController
  40. {
  41.     /**
  42.      * @var PurchaseFlow
  43.      */
  44.     protected $purchaseFlow;
  45.     /**
  46.      * @var CustomerFavoriteProductRepository
  47.      */
  48.     protected $customerFavoriteProductRepository;
  49.     /**
  50.      * @var CartService
  51.      */
  52.     protected $cartService;
  53.     /**
  54.      * @var ProductRepository
  55.      */
  56.     protected $productRepository;
  57.     /**
  58.      * @var BaseInfo
  59.      */
  60.     protected $BaseInfo;
  61.     /**
  62.      * @var AuthenticationUtils
  63.      */
  64.     protected $helper;
  65.     /**
  66.      * @var ProductListMaxRepository
  67.      */
  68.     protected $productListMaxRepository;
  69.     private $title '';
  70.     /**
  71.      * ProductController constructor.
  72.      *
  73.      * @param PurchaseFlow $cartPurchaseFlow
  74.      * @param CustomerFavoriteProductRepository $customerFavoriteProductRepository
  75.      * @param CartService $cartService
  76.      * @param ProductRepository $productRepository
  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.         BaseInfoRepository $baseInfoRepository,
  87.         AuthenticationUtils $helper,
  88.         ProductListMaxRepository $productListMaxRepository,
  89.         ConfigRepository $ConfigRepository
  90.     ) {
  91.         $this->purchaseFlow $cartPurchaseFlow;
  92.         $this->customerFavoriteProductRepository $customerFavoriteProductRepository;
  93.         $this->cartService $cartService;
  94.         $this->productRepository $productRepository;
  95.         $this->BaseInfo $baseInfoRepository->get();
  96.         $this->helper $helper;
  97.         $this->productListMaxRepository $productListMaxRepository;
  98.         $this->ConfigRepository $ConfigRepository;
  99.     }
  100.     /**
  101.      * 商品一覧画面.
  102.      *
  103.      * @Route("/products/list", name="product_list", methods={"GET"})
  104.      * @Template("Product/list.twig")
  105.      */
  106.     public function index(Request $requestPaginatorInterface $paginator)
  107.     {
  108.         // Doctrine SQLFilter
  109.         if ($this->BaseInfo->isOptionNostockHidden()) {
  110.             $this->entityManager->getFilters()->enable('option_nostock_hidden');
  111.         }
  112.         // handleRequestは空のqueryの場合は無視するため
  113.         if ($request->getMethod() === 'GET') {
  114.             $request->query->set('pageno'$request->query->get('pageno'''));
  115.         }
  116.         // searchForm
  117.         /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  118.         $builder $this->formFactory->createNamedBuilder(''SearchProductType::class);
  119.         if ($request->getMethod() === 'GET') {
  120.             $builder->setMethod('GET');
  121.         }
  122.         $event = new EventArgs(
  123.             [
  124.                 'builder' => $builder,
  125.             ],
  126.             $request
  127.         );
  128.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_INITIALIZE);
  129.         /* @var $searchForm \Symfony\Component\Form\FormInterface */
  130.         $searchForm $builder->getForm();
  131.         $searchForm->handleRequest($request);
  132.         // paginator
  133.         $searchData $searchForm->getData();
  134.         $qb $this->productRepository->getQueryBuilderBySearchData($searchData);
  135.         $event = new EventArgs(
  136.             [
  137.                 'searchData' => $searchData,
  138.                 'qb' => $qb,
  139.             ],
  140.             $request
  141.         );
  142.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_SEARCH);
  143.         $searchData $event->getArgument('searchData');
  144.         // 価格帯パラメータを searchData に追加 → Repository側で処理
  145.         $priceMin $request->query->get('price_min');
  146.         $priceMax $request->query->get('price_max');
  147.         if ($priceMin !== null && $priceMin !== '') {
  148.             $searchData['price_min'] = $priceMin;
  149.         }
  150.         if ($priceMax !== null && $priceMax !== '') {
  151.             $searchData['price_max'] = $priceMax;
  152.         }
  153.         // searchData を更新したので qb を再構築
  154.         if (isset($searchData['price_min']) || isset($searchData['price_max'])) {
  155.             $qb $this->productRepository->getQueryBuilderBySearchData($searchData);
  156.         }
  157.         $query $qb->getQuery()
  158.             ->useResultCache(true$this->eccubeConfig['eccube_result_cache_lifetime_short']);
  159.         /** @var SlidingPagination $pagination */
  160.         $pagination $paginator->paginate(
  161.             $query,
  162.             !empty($searchData['pageno']) ? $searchData['pageno'] : 1,
  163.             !empty($searchData['disp_number']) ? $searchData['disp_number']->getId() : $this->productListMaxRepository->findOneBy([], ['sort_no' => 'ASC'])->getId()
  164.         );
  165.         $ids = [];
  166.         foreach ($pagination as $Product) {
  167.             $ids[] = $Product->getId();
  168.         }
  169.         $ProductsAndClassCategories $this->productRepository->findProductsWithSortedClassCategories($ids'p.id');
  170.         // addCart form
  171.         $forms = [];
  172.         foreach ($pagination as $Product) {
  173.             /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  174.             $builder $this->formFactory->createNamedBuilder(
  175.                 '',
  176.                 AddCartType::class,
  177.                 null,
  178.                 [
  179.                     'product' => $ProductsAndClassCategories[$Product->getId()],
  180.                     'allow_extra_fields' => true,
  181.                 ]
  182.             );
  183.             $addCartForm $builder->getForm();
  184.             $forms[$Product->getId()] = $addCartForm->createView();
  185.         }
  186.         $Category $searchForm->get('category_id')->getData();
  187.         $Maker $searchForm->get('maker_id')->getData();
  188.         return [
  189.             'subtitle' => $this->getPageTitle($searchData),
  190.             'pagination' => $pagination,
  191.             'search_form' => $searchForm->createView(),
  192.             'forms' => $forms,
  193.             'Category' => $Category,
  194.             'Maker' => $Maker,
  195.         ];
  196.     }
  197.     /**
  198.      * 商品詳細画面.
  199.      *
  200.      * @Route("/products/detail/{id}", name="product_detail", methods={"GET"}, requirements={"id" = "\d+"})
  201.      * @Template("Product/detail.twig")
  202.      * @ParamConverter("Product", options={"repository_method" = "findWithSortedClassCategories"})
  203.      *
  204.      * @param Request $request
  205.      * @param Product $Product
  206.      *
  207.      * @return array
  208.      */
  209.     public function detail(Request $requestProduct $Product)
  210.     {
  211.         if (!$this->checkVisibility($Product)) {
  212.             throw new NotFoundHttpException();
  213.         }
  214.         $builder $this->formFactory->createNamedBuilder(
  215.             '',
  216.             AddCartType::class,
  217.             null,
  218.             [
  219.                 'product' => $Product,
  220.                 'id_add_product_id' => false,
  221.             ]
  222.         );
  223.     
  224.         $event = new EventArgs(
  225.             [
  226.                 'builder' => $builder,
  227.                 'Product' => $Product,
  228.             ],
  229.             $request
  230.         );
  231.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE);
  232.         $is_favorite false;
  233.         if ($this->isGranted('ROLE_USER')) {
  234.             $Customer $this->getUser();
  235.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  236.         }
  237.         // Helper: unserialize that never throws / never returns false-shaped value.
  238.         // Returns array() for null/empty/corrupted/non-array payloads.
  239.         $safeUnserialize = static function ($raw): array {
  240.             if (!is_string($raw) || $raw === '') {
  241.                 return [];
  242.             }
  243.             $decoded = @unserialize($raw);
  244.             return is_array($decoded) ? $decoded : [];
  245.         };
  246.         $color $safeUnserialize($Product->getSearchWord());
  247.         $pp = array();
  248.         $p_w = array();
  249.         $p_d = array();
  250.         $p_h = array();
  251.         $p_m = array();
  252.         $p_c = array();
  253.         $p_option1 = array();
  254.         $p_option2 = array();
  255.         $pp_price $safeUnserialize($Product->getFreeArea());
  256.         foreach($pp_price as $key => $item){
  257.             if(!is_array($item)) continue;
  258.             if(empty($item['ct'])){ $item['ct'] = 0; }
  259.             $pp[] = $item;
  260.             if(isset($item['w'])) $p_w[$item['w']] = $item['w'];
  261.             if(isset($item['c'])) $p_c[$item['c']] = $item['c'];
  262.             if(isset($item['d'])) $p_d[$item['d']] = $item['d'];
  263.             if(isset($item['h'])) $p_h[$item['h']] = $item['h'];
  264.             if(isset($item['m'])) $p_m[$item['m']] = $item['m'];
  265.             if(isset($item['option1']) && $item['option1'] !== ''$p_option1[$item['option1']] = $item['option1'];
  266.             if(isset($item['option2']) && $item['option2'] !== ''$p_option2[$item['option2']] = $item['option2'];
  267.         }
  268.         $op $safeUnserialize($Product->getOptionArea());
  269.         // option_item_area: 複数カテゴリで使われる差額表構造を保存
  270.         //   ['axis_labels' => ['F'=>'床材',...], 'blocks' => ['W|D' => ['F'=>[{idx,label,diff},...], ...], ...]]
  271.         //     — tg 用 (block 別オプション差額)
  272.         //   ['fe_block' => ['depends_on_index' => N, 'depends_on_value' => 'XXX',
  273.         //                   'title' => '...', 'default_key' => '...',
  274.         //                   'choices' => [{key,label,price}, ...]]]
  275.         //     — fe (sale_type=4) 用「ブロックの種類×段数」差額表
  276.         // 旧 OptionItem 用途は未完成のため使用していない. 構造が array でなければ空とする.
  277.         $oi_data $safeUnserialize($Product->getOptionItemArea());
  278.         $oi is_array($oi_data) ? $oi_data : [];
  279.         if (!isset($oi['axis_labels']) || !is_array($oi['axis_labels'])) {
  280.             $oi['axis_labels'] = [];
  281.         }
  282.         if (!isset($oi['blocks']) || !is_array($oi['blocks'])) {
  283.             $oi['blocks'] = [];
  284.         }
  285.         if (!isset($oi['fe_block']) || !is_array($oi['fe_block'])
  286.             || empty($oi['fe_block']['choices']) || !is_array($oi['fe_block']['choices'])) {
  287.             $oi['fe_block'] = null;
  288.         }
  289.         $ProductClasses $Product->getProductClasses();
  290.         $ProductClass $ProductClasses[0];
  291.         // related_product meta may be missing entirely for products
  292.         // imported through the scraper. Guard against null Configs and
  293.         // corrupted/empty serialized payloads.
  294.         $Configs $this->ConfigRepository->joinMetaKeyFind($Product->getId(),'related_product');
  295.         $meta_array $safeUnserialize($Configs["b_meta_content"] ?? null);
  296.         $meta_array[] = $Product->getId();
  297.         $related_product $this->productRepository->findBy(["id" => $meta_array,'Status' => 1]);
  298.         $related_keyword $this->ConfigRepository->joinMetaKeyFind($Product->getId(),'related_keyword');
  299.         $base_select1 $this->ConfigRepository->joinMetaKeyFind($Product->getId(),'related_selected1');
  300.         $base_select2 $this->ConfigRepository->joinMetaKeyFind($Product->getId(),'related_selected2');
  301.         $base_select3 $this->ConfigRepository->joinMetaKeyFind($Product->getId(),'related_selected3');
  302.         $base_select4 $this->ConfigRepository->joinMetaKeyFind($Product->getId(),'related_selected4');
  303.         $related_product1 = array();
  304.         $related_product2 = array();
  305.         $related_product3 = array();
  306.         $related_product4 = array();
  307.         $registed_select1 = array();
  308.         $registed_select2 = array();
  309.         $registed_select3 = array();
  310.         $registed_select4 = array();
  311.         $rrp = array();
  312.         foreach($related_product as $rp){
  313.             $select_name1 $this->ConfigRepository->joinMetaKeyFind($rp->getId(),'related_selected1');
  314.             $select_name2 $this->ConfigRepository->joinMetaKeyFind($rp->getId(),'related_selected2');
  315.             $select_name3 $this->ConfigRepository->joinMetaKeyFind($rp->getId(),'related_selected3');
  316.             $select_name4 $this->ConfigRepository->joinMetaKeyFind($rp->getId(),'related_selected4');
  317.             $rrp[] = $rp->getId();
  318.             if(!in_array($select_name1["b_meta_content"],$registed_select1)){
  319.                 $registed_select1[$select_name1["b_meta_content"]] = $select_name1["b_meta_content"];
  320.                 $related_product1[$rp->getId()] = $select_name1["b_meta_content"];
  321.                 if(preg_match("/スタンダード|片側|フラット|ノーマル/",$related_product1[$rp->getId()])){
  322.                     $related_product1[$rp->getId()] = "[1]".$related_product1[$rp->getId()];
  323.                 }
  324.                 if(preg_match("/プレミアム|両側|ラウンド|幅広/",$related_product1[$rp->getId()])){
  325.                     $related_product1[$rp->getId()] = "[2]".$related_product1[$rp->getId()];
  326.                 }
  327.                 if(preg_match("/デラックス|後方|アーチ|外壁接続/",$related_product1[$rp->getId()])){
  328.                     $related_product1[$rp->getId()] = "[3]".$related_product1[$rp->getId()];
  329.                 }
  330.                 if(preg_match("/屋根/",$related_product1[$rp->getId()])){
  331.                     $related_product1[$rp->getId()] = "[4]".$related_product1[$rp->getId()];
  332.                 }
  333.             }
  334.             if(!in_array($select_name2["b_meta_content"],$registed_select2) && $base_select1["b_meta_content"] == $select_name1["b_meta_content"]){
  335.                 $registed_select2[$select_name2["b_meta_content"]] = $select_name2["b_meta_content"];
  336.                 $related_product2[$rp->getId()] = $select_name2["b_meta_content"];
  337.                 if(preg_match("/スタンダード|片側|フラット|ノーマル/",$related_product2[$rp->getId()])){
  338.                     $related_product2[$rp->getId()] = "[1]".$related_product2[$rp->getId()];
  339.                 }
  340.                 if(preg_match("/プレミアム|両側|ラウンド|幅広/",$related_product2[$rp->getId()])){
  341.                     $related_product2[$rp->getId()] = "[2]".$related_product2[$rp->getId()];
  342.                 }
  343.                 if(preg_match("/デラックス|後方|アーチ|外壁接続/",$related_product2[$rp->getId()])){
  344.                     $related_product2[$rp->getId()] = "[3]".$related_product2[$rp->getId()];
  345.                 }
  346.                 if(preg_match("/屋根/",$related_product2[$rp->getId()])){
  347.                     $related_product2[$rp->getId()] = "[4]".$related_product2[$rp->getId()];
  348.                 }
  349.             }
  350.             if(!in_array($select_name3["b_meta_content"],$registed_select3) && $base_select1["b_meta_content"] == $select_name1["b_meta_content"] && $base_select2["b_meta_content"] == $select_name2["b_meta_content"]){
  351.                 $registed_select3[$select_name3["b_meta_content"]] = $select_name3["b_meta_content"];
  352.                 $related_product3[$rp->getId()] = $select_name3["b_meta_content"];
  353.                 if(preg_match("/スタンダード|片側|フラット|ノーマル/",$related_product3[$rp->getId()])){
  354.                     $related_product3[$rp->getId()] = "[1]".$related_product3[$rp->getId()];
  355.                 }
  356.                 if(preg_match("/プレミアム|両側|ラウンド|幅広/",$related_product3[$rp->getId()])){
  357.                     $related_product3[$rp->getId()] = "[2]".$related_product3[$rp->getId()];
  358.                 }
  359.                 if(preg_match("/デラックス|後方|アーチ|外壁接続/",$related_product3[$rp->getId()])){
  360.                     $related_product3[$rp->getId()] = "[3]".$related_product3[$rp->getId()];
  361.                 }
  362.                 if(preg_match("/屋根/",$related_product3[$rp->getId()])){
  363.                     $related_product3[$rp->getId()] = "[4]".$related_product3[$rp->getId()];
  364.                 }
  365.             }
  366.             if(!in_array($select_name4["b_meta_content"],$registed_select4) && $base_select1["b_meta_content"] == $select_name1["b_meta_content"] && $base_select2["b_meta_content"] == $select_name2["b_meta_content"] && $base_select3["b_meta_content"] == $select_name3["b_meta_content"]){
  367.                 $registed_select4[$select_name4["b_meta_content"]] = $select_name4["b_meta_content"];
  368.                 $related_product4[$rp->getId()] = $select_name4["b_meta_content"];
  369.                 if(preg_match("/スタンダード|片側|フラット|ノーマル/",$related_product4[$rp->getId()])){
  370.                     $related_product4[$rp->getId()] = "[1]".$related_product4[$rp->getId()];
  371.                 }
  372.                 if(preg_match("/プレミアム|両側|ラウンド|幅広/",$related_product4[$rp->getId()])){
  373.                     $related_product4[$rp->getId()] = "[2]".$related_product4[$rp->getId()];
  374.                 }
  375.                 if(preg_match("/デラックス|後方|アーチ|外壁接続/",$related_product4[$rp->getId()])){
  376.                     $related_product4[$rp->getId()] = "[3]".$related_product4[$rp->getId()];
  377.                 }
  378.                 if(preg_match("/屋根/",$related_product4[$rp->getId()])){
  379.                     $related_product4[$rp->getId()] = "[4]".$related_product4[$rp->getId()];
  380.                 }
  381.             }
  382.         }
  383.         asort($related_product1,SORT_NATURAL);
  384.         asort($related_product1,SORT_NUMERIC);
  385.         asort($related_product2,SORT_NATURAL);
  386.         asort($related_product2,SORT_NUMERIC);
  387.         asort($related_product3,SORT_NATURAL);
  388.         asort($related_product3,SORT_NUMERIC);
  389.         asort($related_product4,SORT_NATURAL);
  390.         asort($related_product4,SORT_NUMERIC);
  391.         foreach($related_product1 as $rp_id => $rd_value){
  392.             $rd_value preg_replace('/\[[0-9]+\]/'''$rd_value);
  393.             $related_product1[$rp_id] = $rd_value;
  394.         }
  395.         foreach($related_product2 as $rp_id => $rd_value){
  396.             $rd_value preg_replace('/\[[0-9]+\]/'''$rd_value);
  397.             $related_product2[$rp_id] = $rd_value;
  398.         }
  399.         foreach($related_product3 as $rp_id => $rd_value){
  400.             $rd_value preg_replace('/\[[0-9]+\]/'''$rd_value);
  401.             $related_product3[$rp_id] = $rd_value;
  402.         }
  403.         foreach($related_product4 as $rp_id => $rd_value){
  404.             $rd_value preg_replace('/\[[0-9]+\]/'''$rd_value);
  405.             $related_product4[$rp_id] = $rd_value;
  406.         }
  407.         $mitsumori_json = @$_SESSION['mitsumori_json'];
  408.         if(empty($mitsumori_json)){ $mitsumori_json "{product_id:0, pw:'',pd:'',ph:'',pm:'',pc:'',op:['','','','','','','','','','','']}"; }
  409.         $mitsumori_json_obj json_decode($mitsumori_json);
  410.         if(empty($mitsumori_json_obj) || $mitsumori_json_obj->product_id != $Product->getId()){
  411.             // セッションなし or 別商品 → pp_priceの最安値パターンを初期値にセット
  412.             $mitsumori_json_obj = new \stdClass();
  413.             $mitsumori_json_obj->product_id 0;
  414.             $mitsumori_json_obj->pw '';
  415.             $mitsumori_json_obj->pd '';
  416.             $mitsumori_json_obj->ph '';
  417.             $mitsumori_json_obj->pm '';
  418.             $mitsumori_json_obj->pc '';
  419.             $mitsumori_json_obj->op = ['','','','','','','','','','',''];
  420.             if (!empty($pp_price)) {
  421.                 // $item['price'] が最小のアイテムを取得
  422.                 $cheapest null;
  423.                 foreach ($pp_price as $item) {
  424.                     $itemPrice = (int) $item['price'];
  425.                     if ($cheapest === null || $itemPrice < (int) $cheapest['price']) {
  426.                         $cheapest $item;
  427.                     }
  428.                 }
  429.                 if ($cheapest !== null) {
  430.                     $mitsumori_json_obj->pw $cheapest['w'] ?? '';
  431.                     $mitsumori_json_obj->pd $cheapest['d'] ?? '';
  432.                     $mitsumori_json_obj->ph $cheapest['h'] ?? '';
  433.                     $mitsumori_json_obj->pm $cheapest['m'] ?? '';
  434.                     $mitsumori_json_obj->pc $cheapest['c'] ?? '';
  435.                 }
  436.             }
  437.         }
  438.         return [
  439.             'title' => $this->title,
  440.             'subtitle' => $Product->getName(),
  441.             'form' => $builder->getForm()->createView(),
  442.             'Product' => $Product,
  443.             'color' => $color,
  444.             'pp' => json_encode($pp),
  445.             'base_select1' => @$base_select1["b_meta_content"],
  446.             'base_select2' => @$base_select2["b_meta_content"],
  447.             'base_select3' => @$base_select3["b_meta_content"],
  448.             'base_select4' => @$base_select4["b_meta_content"],
  449.             'related_product1' => $related_product1,
  450.             'related_product2' => $related_product2,
  451.             'related_product3' => $related_product3,
  452.             'related_product4' => $related_product4,
  453.             'mitsumori_json' => $mitsumori_json_obj,
  454.             'p_w' => $p_w,
  455.             'p_d' => $p_d,
  456.             'p_h' => $p_h,
  457.             'p_m' => $p_m,
  458.             'p_c' => $p_c,
  459.             'p_option1' => $p_option1,
  460.             'p_option2' => $p_option2,
  461.             'op' => $op,
  462.             'op_json' => json_encode(is_array($op) ? array_values($op) : []),
  463.             'oi' => $oi,
  464.             'oi_json' => json_encode($oiJSON_UNESCAPED_UNICODE),
  465.             'ProductClass' => $ProductClass,
  466.             'is_favorite' => $is_favorite,
  467.         ];
  468.     }
  469.     /**
  470.      * お気に入り追加.
  471.      *
  472.      * @Route("/products/add_favorite/{id}", name="product_add_favorite", requirements={"id" = "\d+"}, methods={"GET", "POST"})
  473.      */
  474.     public function addFavorite(Request $requestProduct $Product)
  475.     {
  476.         $this->checkVisibility($Product);
  477.         $event = new EventArgs(
  478.             [
  479.                 'Product' => $Product,
  480.             ],
  481.             $request
  482.         );
  483.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_INITIALIZE);
  484.         if ($this->isGranted('ROLE_USER')) {
  485.             $Customer $this->getUser();
  486.             $this->customerFavoriteProductRepository->addFavorite($Customer$Product);
  487.             $this->session->getFlashBag()->set('product_detail.just_added_favorite'$Product->getId());
  488.             $event = new EventArgs(
  489.                 [
  490.                     'Product' => $Product,
  491.                 ],
  492.                 $request
  493.             );
  494.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  495.             return $this->redirectToRoute('product_detail', ['id' => $Product->getId()]);
  496.         } else {
  497.             // 非会員の場合、ログイン画面を表示
  498.             //  ログイン後の画面遷移先を設定
  499.             $this->setLoginTargetPath($this->generateUrl('product_add_favorite', ['id' => $Product->getId()], UrlGeneratorInterface::ABSOLUTE_URL));
  500.             $this->session->getFlashBag()->set('eccube.add.favorite'true);
  501.             $event = new EventArgs(
  502.                 [
  503.                     'Product' => $Product,
  504.                 ],
  505.                 $request
  506.             );
  507.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_FAVORITE_ADD_COMPLETE);
  508.             return $this->redirectToRoute('mypage_login');
  509.         }
  510.     }
  511.     /**
  512.      * カートに追加.
  513.      *
  514.      * @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
  515.      */
  516.     public function addCart(Request $requestProduct $Product)
  517.     {
  518.         if(!empty($_POST['mitsumori_json'])){
  519.             $_SESSION['mitsumori_json'] = $_POST['mitsumori_json'];
  520.         }
  521.         // エラーメッセージの配列
  522.         $errorMessages = [];
  523.         if (!$this->checkVisibility($Product)) {
  524.             throw new NotFoundHttpException();
  525.         }
  526.         $builder $this->formFactory->createNamedBuilder(
  527.             '',
  528.             AddCartType::class,
  529.             null,
  530.             [
  531.                 'product' => $Product,
  532.                 'id_add_product_id' => false,
  533.             ]
  534.         );
  535.         $event = new EventArgs(
  536.             [
  537.                 'builder' => $builder,
  538.                 'Product' => $Product,
  539.             ],
  540.             $request
  541.         );
  542.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE);
  543.         /* @var $form \Symfony\Component\Form\FormInterface */
  544.         $form $builder->getForm();
  545.         $form->handleRequest($request);
  546.         if (!$form->isValid()) {
  547.             throw new NotFoundHttpException();
  548.         }
  549.         $addCartData $form->getData();
  550.         log_info(
  551.             'カート追加処理開始',
  552.             [
  553.                 'product_id' => $Product->getId(),
  554.                 'product_class_id' => $addCartData['product_class_id'],
  555.                 'quantity' => $addCartData['quantity'],
  556.             ]
  557.         );
  558.         $ProductClass $this->entityManager->getRepository(ProductClass::class)->find($addCartData['product_class_id']);
  559.         $ProductClass->setMitsumoriJSON(@$_POST['mitsumori_json']);
  560.         // カートへ追加
  561.         $this->cartService->addProduct($ProductClass$addCartData['quantity']);
  562.         // 明細の正規化
  563.         $Carts $this->cartService->getCarts();
  564.         foreach ($Carts as $Cart) {
  565.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  566.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  567.             if ($result->hasError()) {
  568.                 $this->cartService->removeProduct($addCartData['product_class_id']);
  569.                 foreach ($result->getErrors() as $error) {
  570.                     $errorMessages[] = $error->getMessage();
  571.                 }
  572.             }
  573.             foreach ($result->getWarning() as $warning) {
  574.                 $errorMessages[] = $warning->getMessage();
  575.             }
  576.         }
  577.         $this->cartService->save();
  578.         log_info(
  579.             'カート追加処理完了',
  580.             [
  581.                 'product_id' => $Product->getId(),
  582.                 'product_class_id' => $addCartData['product_class_id'],
  583.                 'quantity' => $addCartData['quantity'],
  584.             ]
  585.         );
  586.         $event = new EventArgs(
  587.             [
  588.                 'form' => $form,
  589.                 'Product' => $Product,
  590.             ],
  591.             $request
  592.         );
  593.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE);
  594.         if ($event->getResponse() !== null) {
  595.             return $event->getResponse();
  596.         }
  597.         if ($request->isXmlHttpRequest()) {
  598.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  599.             // 初期化
  600.             $messages = [];
  601.             if (empty($errorMessages)) {
  602.                 // エラーが発生していない場合
  603.                 $done true;
  604.                 array_push($messagestrans('front.product.add_cart_complete'));
  605.             } else {
  606.                 // エラーが発生している場合
  607.                 $done false;
  608.                 $messages $errorMessages;
  609.             }
  610.             return $this->json(['done' => $done'messages' => $messages]);
  611.         } else {
  612.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  613.             foreach ($errorMessages as $errorMessage) {
  614.                 $this->addRequestError($errorMessage);
  615.             }
  616.             return $this->redirectToRoute('cart');
  617.         }
  618.     }
  619.     /**
  620.      * ページタイトルの設定
  621.      *
  622.      * @param  array|null $searchData
  623.      *
  624.      * @return str
  625.      */
  626.     protected function getPageTitle($searchData)
  627.     {
  628.         if (isset($searchData['name']) && !empty($searchData['name'])) {
  629.             return trans('front.product.search_result');
  630.         } elseif (isset($searchData['category_id']) && $searchData['category_id']) {
  631.             return $searchData['category_id']->getName();
  632.         } else {
  633.             return trans('front.product.all_products');
  634.         }
  635.     }
  636.     /**
  637.      * 閲覧可能な商品かどうかを判定
  638.      *
  639.      * @param Product $Product
  640.      *
  641.      * @return boolean 閲覧可能な場合はtrue
  642.      */
  643.     protected function checkVisibility(Product $Product)
  644.     {
  645.         $is_admin $this->session->has('_security_admin');
  646.         // 管理ユーザの場合はステータスやオプションにかかわらず閲覧可能.
  647.         if (!$is_admin) {
  648.             // 在庫なし商品の非表示オプションが有効な場合.
  649.             // if ($this->BaseInfo->isOptionNostockHidden()) {
  650.             //     if (!$Product->getStockFind()) {
  651.             //         return false;
  652.             //     }
  653.             // }
  654.             // 公開ステータスでない商品は表示しない.
  655.             if ($Product->getStatus()->getId() !== ProductStatus::DISPLAY_SHOW) {
  656.                 return false;
  657.             }
  658.         }
  659.         return true;
  660.     }
  661. }