app/Customize/Controller/ProductController.php line 269

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\Event\EccubeEvents;
  17. use Eccube\Event\EventArgs;
  18. use Eccube\Form\Type\AddCartType;
  19. use Eccube\Controller\AbstractController;
  20. use Eccube\Form\Type\SearchProductType;
  21. use Eccube\Repository\BaseInfoRepository;
  22. use Eccube\Repository\CustomerFavoriteProductRepository;
  23. use Eccube\Repository\Master\ProductListMaxRepository;
  24. use Eccube\Repository\ProductRepository;
  25. use Eccube\Service\CartService;
  26. use Eccube\Service\PurchaseFlow\PurchaseContext;
  27. use Eccube\Service\PurchaseFlow\PurchaseFlow;
  28. use Knp\Bundle\PaginatorBundle\Pagination\SlidingPagination;
  29. use Knp\Component\Pager\PaginatorInterface;
  30. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  31. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  32. use Symfony\Component\HttpFoundation\Request;
  33. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  34. use Symfony\Component\Routing\Annotation\Route;
  35. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  36. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  37. use Customize\Repository\ArtistRepository;
  38. use Customize\Entity\Artist
  39. use Plugin\Maker42\Repository\MakerRepository;
  40. use Customize\Repository\CategoryRepository;
  41. class ProductController extends AbstractController
  42. {
  43.     /**
  44.      * @var PurchaseFlow
  45.      */
  46.     protected $purchaseFlow;
  47.     /**
  48.      * @var CustomerFavoriteProductRepository
  49.      */
  50.     protected $customerFavoriteProductRepository;
  51.     /**
  52.      * @var CartService
  53.      */
  54.     protected $cartService;
  55.     /**
  56.      * @var ProductRepository
  57.      */
  58.     protected $productRepository;
  59.     /**
  60.      * @var BaseInfo
  61.      */
  62.     protected $BaseInfo;
  63.     /**
  64.      * @var AuthenticationUtils
  65.      */
  66.     protected $helper;
  67.     /**
  68.      * @var ProductListMaxRepository
  69.      */
  70.     protected $productListMaxRepository;
  71.     /**
  72.      * @var CategoryRepository
  73.      */
  74.     protected $categoryRepository;
  75.     /**
  76.      * @var ArtistRepository
  77.      */
  78.     protected $artistRepository;
  79.     /**
  80.      * @var MakerRepository
  81.      */
  82.     protected $makerRepository;
  83.     private $title '';
  84.     /**
  85.      * ProductController constructor.
  86.      *
  87.      * @param PurchaseFlow $cartPurchaseFlow
  88.      * @param CustomerFavoriteProductRepository $customerFavoriteProductRepository
  89.      * @param CartService $cartService
  90.      * @param ProductRepository $productRepository
  91.      * @param BaseInfoRepository $baseInfoRepository
  92.      * @param AuthenticationUtils $helper
  93.      * @param ProductListMaxRepository $productListMaxRepository
  94.      * @param CategoryRepository $categoryRepository
  95.      * @param ArtistRepository $artistRepository
  96.      * @param MakerRepository $makerRepository
  97.      */
  98.     public function __construct(
  99.         PurchaseFlow $cartPurchaseFlow,
  100.         CustomerFavoriteProductRepository $customerFavoriteProductRepository,
  101.         CartService $cartService,
  102.         ProductRepository $productRepository,
  103.         BaseInfoRepository $baseInfoRepository,
  104.         AuthenticationUtils $helper,
  105.         ProductListMaxRepository $productListMaxRepository,
  106.         CategoryRepository $categoryRepository,
  107.         ArtistRepository $artistRepository,
  108.         MakerRepository $makerRepository
  109.     ) {
  110.         $this->purchaseFlow $cartPurchaseFlow;
  111.         $this->customerFavoriteProductRepository $customerFavoriteProductRepository;
  112.         $this->cartService $cartService;
  113.         $this->productRepository $productRepository;
  114.         $this->BaseInfo $baseInfoRepository->get();
  115.         $this->helper $helper;
  116.         $this->productListMaxRepository $productListMaxRepository;
  117.         $this->categoryRepository $categoryRepository;
  118.         $this->artistRepository $artistRepository;
  119.         $this->makerRepository $makerRepository;
  120.     }
  121.     /**
  122.      * カテゴリー詳細画面.
  123.      *
  124.      * @Route("/products/feature/{id}", name="product_feature", methods={"GET"})
  125.      * @Template("Product/feature.twig")
  126.      * @ParamConverter("Product", options={"repository_method" = "findWithSortedClassCategories"})
  127.      *
  128.      * @param Request $request
  129.      * @param Product $Product
  130.      *
  131.      * @return array
  132.      */
  133.     public function feature(Request $requestProduct $Product)
  134.     {
  135.         if (!$this->checkVisibility($Product)) {
  136.             throw new NotFoundHttpException();
  137.         }
  138.         $builder $this->formFactory->createNamedBuilder(
  139.             '',
  140.             AddCartType::class,
  141.             null,
  142.             [
  143.                 'product' => $Product,
  144.                 'id_add_product_id' => false,
  145.             ]
  146.         );
  147.         $event = new EventArgs(
  148.             [
  149.                 'builder' => $builder,
  150.                 'Product' => $Product,
  151.             ],
  152.             $request
  153.         );
  154.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE);
  155.         $is_favorite false;
  156.         if ($this->isGranted('ROLE_USER')) {
  157.             $Customer $this->getUser();
  158.             $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  159.         }
  160.         return [
  161.             'title' => $this->title,
  162.             'subtitle' => $Product->getName(),
  163.             'form' => $builder->getForm()->createView(),
  164.             'Product' => $Product,
  165.             'is_favorite' => $is_favorite,
  166.         ];
  167.     }
  168.     /**
  169.      * 商品一覧画面.
  170.      *
  171.      * @Route("/products/list", name="product_list", methods={"GET"})
  172.      * @Template("Product/list.twig")
  173.      */
  174.     public function index(Request $requestPaginatorInterface $paginator)
  175.     {
  176.         $categories $this->categoryRepository->customFindAll();
  177.         // Doctrine SQLFilter
  178.         if ($this->BaseInfo->isOptionNostockHidden()) {
  179.             $this->entityManager->getFilters()->enable('option_nostock_hidden');
  180.         }
  181.         // handleRequestは空のqueryの場合は無視するため
  182.         if ($request->getMethod() === 'GET') {
  183.             $request->query->set('pageno'$request->query->get('pageno'''));
  184.         }
  185.         // searchForm
  186.         /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  187.         $builder $this->formFactory->createNamedBuilder(''SearchProductType::class);
  188.         if ($request->getMethod() === 'GET') {
  189.             $builder->setMethod('GET');
  190.         }
  191.         $event = new EventArgs(
  192.             [
  193.                 'builder' => $builder,
  194.             ],
  195.             $request
  196.         );
  197.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_INITIALIZE);
  198.         /* @var $searchForm \Symfony\Component\Form\FormInterface */
  199.         $searchForm $builder->getForm();
  200.         $searchForm->handleRequest($request);
  201.         // paginator
  202.         $searchData $searchForm->getData();
  203.         $qb $this->productRepository->getQueryBuilderBySearchData($searchData);
  204.         $event = new EventArgs(
  205.             [
  206.                 'searchData' => $searchData,
  207.                 'qb' => $qb,
  208.             ],
  209.             $request
  210.         );
  211.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_INDEX_SEARCH);
  212.         $searchData $event->getArgument('searchData');
  213.         $query $qb->getQuery()
  214.             ->useResultCache(true$this->eccubeConfig['eccube_result_cache_lifetime_short']);
  215.         /** @var SlidingPagination $pagination */
  216.         $pagination $paginator->paginate(
  217.             $query,
  218.             !empty($searchData['pageno']) ? $searchData['pageno'] : 1,
  219.             !empty($searchData['disp_number']) ? $searchData['disp_number']->getId() : $this->productListMaxRepository->findOneBy([], ['sort_no' => 'ASC'])->getId()
  220.         );
  221.         $ids = [];
  222.         foreach ($pagination as $Product) {
  223.             $ids[] = $Product->getId();
  224.         }
  225.         $ProductsAndClassCategories $this->productRepository->findProductsWithSortedClassCategories($ids'p.id');
  226.         // addCart form
  227.         $forms = [];
  228.         foreach ($pagination as $Product) {
  229.             /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
  230.             $builder $this->formFactory->createNamedBuilder(
  231.                 '',
  232.                 AddCartType::class,
  233.                 null,
  234.                 [
  235.                     'product' => $ProductsAndClassCategories[$Product->getId()],
  236.                     'allow_extra_fields' => true,
  237.                 ]
  238.             );
  239.             $addCartForm $builder->getForm();
  240.             $forms[$Product->getId()] = $addCartForm->createView();
  241.         }
  242.         $Category $searchForm->get('category_id')->getData();
  243.         $artists $this->artistRepository->customFindAllArtist();
  244.         $name $request->query->get('name');
  245.         $price_min $request->query->get('price_min');
  246.         $price_max $request->query->get('price_max');
  247.         $size_vertical_min $request->query->get('size_vertical_min');
  248.         $size_vertical_max $request->query->get('size_vertical_max');
  249.         $size_width_min $request->query->get('size_width_min');
  250.         $size_width_max $request->query->get('size_width_max');
  251.         return [
  252.             // 'subtitle' => $this->getPageTitle($searchData),  //なぜかこれのコメントアウト外すとエラー出るので後で調査
  253.             'pagination' => $pagination,
  254.             'search_form' => $searchForm->createView(),
  255.             'forms' => $forms,
  256.             'Category' => $Category,
  257.             'categories' => $categories,
  258.             'artists' => $artists,
  259.             'name' => $name,
  260.             'price_min' => $price_min,
  261.             'price_max' => $price_max,
  262.             'size_vertical_min' => $size_vertical_min,
  263.             'size_vertical_max' => $size_vertical_max,
  264.             'size_width_min' => $size_width_min,
  265.             'size_width_max' => $size_width_max,
  266.         ];
  267.     }
  268.     // cookieの設定の関係で、{maker_id}を持つ場合でも持たない場合でもURLのnameは同一
  269.     /**
  270.      * 商品詳細画面.
  271.      *
  272.      * @Route("/products/detail/{id}", name="product_detail", methods={"GET"}, requirements={"id" = "\d+"})
  273.      * @Route("/products/detail/{id}/{maker_id}", name="product_detail", methods={"GET"}, requirements={"id" = "\d+"}, requirements={"maker_id" = "\d+"})
  274.      * @Template("Product/detail.twig")
  275.      * @ParamConverter("Product", options={"repository_method" = "findWithSortedClassCategories"})
  276.      *
  277.      * @param Request $request
  278.      * @param Product $Product
  279.      *
  280.      * @return array
  281.      */
  282.     public function detail(Request $requestProduct $Product, ?int $maker_id null)
  283.     {
  284.         if (is_null($maker_id) || !($maker_id)) {
  285.             if (!$this->checkVisibility($Product)) {
  286.                 throw new NotFoundHttpException();
  287.             }
  288.             $categories $this->categoryRepository->customFindAll();
  289.             $builder $this->formFactory->createNamedBuilder(
  290.                 '',
  291.                 AddCartType::class,
  292.                 null,
  293.                 [
  294.                     'product' => $Product,
  295.                     'id_add_product_id' => false,
  296.                 ]
  297.             );
  298.             $event = new EventArgs(
  299.                 [
  300.                     'builder' => $builder,
  301.                     'Product' => $Product,
  302.                 ],
  303.                 $request
  304.             );
  305.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE);
  306.             $is_favorite false;
  307.             if ($this->isGranted('ROLE_USER')) {
  308.                 $Customer $this->getUser();
  309.                 $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  310.             }
  311.             $artists $this->artistRepository->customFindAllArtist();
  312.             $products $this->productRepository->findAll();
  313.             // $cookie = $_COOKIE['productHistory'];
  314.             return [
  315.                 "products" => $products,
  316.                 'title' => $this->title,
  317.                 'subtitle' => $Product->getName(),
  318.                 'form' => $builder->getForm()->createView(),
  319.                 'Product' => $Product,
  320.                 'is_favorite' => $is_favorite,
  321.                 'categories' => $categories,
  322.                 'artists' => $artists,
  323.             ];
  324.         } else {                  //qrコードからきた時
  325.             if (!$this->checkVisibility($Product)) {
  326.                 throw new NotFoundHttpException();
  327.             }
  328.             $categories $this->categoryRepository->customFindAll();
  329.             $builder $this->formFactory->createNamedBuilder(
  330.                 '',
  331.                 AddCartType::class,
  332.                 null,
  333.                 [
  334.                     'product' => $Product,
  335.                     'id_add_product_id' => false,
  336.                 ]
  337.             );
  338.             $event = new EventArgs(
  339.                 [
  340.                     'builder' => $builder,
  341.                     'Product' => $Product,
  342.                 ],
  343.                 $request
  344.             );
  345.             $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_DETAIL_INITIALIZE);
  346.             $is_favorite false;
  347.             if ($this->isGranted('ROLE_USER')) {
  348.                 $Customer $this->getUser();
  349.                 $is_favorite $this->customerFavoriteProductRepository->isFavorite($Customer$Product);
  350.             }
  351.             $artists $this->artistRepository->customFindAllArtist();
  352.             $products $this->productRepository->findAll();
  353.             $maker $this->makerRepository->customFindAllArtist();
  354.             return [
  355.                 "products" => $products,
  356.                 'title' => $this->title,
  357.                 'subtitle' => $Product->getName(),
  358.                 'form' => $builder->getForm()->createView(),
  359.                 'Product' => $Product,
  360.                 'is_favorite' => $is_favorite,
  361.                 'categories' => $categories,
  362.                 'artists' => $artists,
  363.                 'maker_id' => $maker_id,
  364.                 'maker' => $maker,
  365.             ];
  366.         }
  367.     }
  368.     /**
  369.      * カートに追加.
  370.      *
  371.      * @Route("/products/add_cart/{id}", name="product_add_cart", methods={"POST"}, requirements={"id" = "\d+"})
  372.      */
  373.     public function addCart(Request $requestProduct $Product)
  374.     {
  375.         // エラーメッセージの配列
  376.         $errorMessages = [];
  377.         if (!$this->checkVisibility($Product)) {
  378.             throw new NotFoundHttpException();
  379.         }
  380.         $builder $this->formFactory->createNamedBuilder(
  381.             '',
  382.             AddCartType::class,
  383.             null,
  384.             [
  385.                 'product' => $Product,
  386.                 'id_add_product_id' => false,
  387.             ]
  388.         );
  389.         $event = new EventArgs(
  390.             [
  391.                 'builder' => $builder,
  392.                 'Product' => $Product,
  393.             ],
  394.             $request
  395.         );
  396.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_INITIALIZE);
  397.         /* @var $form \Symfony\Component\Form\FormInterface */
  398.         $form $builder->getForm();
  399.         $form->handleRequest($request);
  400.         if (!$form->isValid()) {
  401.             throw new NotFoundHttpException();
  402.         }
  403.         $addCartData $form->getData();
  404.         log_info(
  405.             'カート追加処理開始',
  406.             [
  407.                 'product_id' => $Product->getId(),
  408.                 'product_class_id' => $addCartData['product_class_id'],
  409.                 'quantity' => $addCartData['quantity'],
  410.                 'maker_id' => $addCartData['maker_id'],
  411.             ]
  412.         );
  413.         // カートへ追加
  414.         $this->cartService->addProduct($addCartData['product_class_id'], $addCartData['quantity'], $addCartData['maker_id']);
  415.         // 明細の正規化
  416.         $Carts $this->cartService->getCarts();
  417.         foreach ($Carts as $Cart) {
  418.             $result $this->purchaseFlow->validate($Cart, new PurchaseContext($Cart$this->getUser()));
  419.             // 復旧不可のエラーが発生した場合は追加した明細を削除.
  420.             if ($result->hasError()) {
  421.                 $this->cartService->removeProduct($addCartData['product_class_id']);
  422.                 foreach ($result->getErrors() as $error) {
  423.                     $errorMessages[] = $error->getMessage();
  424.                 }
  425.             }
  426.             foreach ($result->getWarning() as $warning) {
  427.                 $errorMessages[] = $warning->getMessage();
  428.             }
  429.         }
  430.         $this->cartService->save();
  431.         log_info(
  432.             'カート追加処理完了',
  433.             [
  434.                 'product_id' => $Product->getId(),
  435.                 'product_class_id' => $addCartData['product_class_id'],
  436.                 'quantity' => $addCartData['quantity'],
  437.                 'maker_id' => $addCartData['maker_id'],
  438.             ]
  439.         );
  440.         $event = new EventArgs(
  441.             [
  442.                 'form' => $form,
  443.                 'Product' => $Product,
  444.             ],
  445.             $request
  446.         );
  447.         $this->eventDispatcher->dispatch($eventEccubeEvents::FRONT_PRODUCT_CART_ADD_COMPLETE);
  448.         if ($event->getResponse() !== null) {
  449.             return $event->getResponse();
  450.         }
  451.         if ($request->isXmlHttpRequest()) {
  452.             // ajaxでのリクエストの場合は結果をjson形式で返す。
  453.             // 初期化
  454.             $messages = [];
  455.             if (empty($errorMessages)) {
  456.                 // エラーが発生していない場合
  457.                 $done true;
  458.                 array_push($messagestrans('front.product.add_cart_complete'));
  459.             } else {
  460.                 // エラーが発生している場合
  461.                 $done false;
  462.                 $messages $errorMessages;
  463.             }
  464.             return $this->json(['done' => $done'messages' => $messages]);
  465.         } else {
  466.             // ajax以外でのリクエストの場合はカート画面へリダイレクト
  467.             foreach ($errorMessages as $errorMessage) {
  468.                 $this->addRequestError($errorMessage);
  469.             }
  470.             return $this->redirectToRoute('cart');
  471.         }
  472.     }
  473.     /**
  474.      * 閲覧可能な商品かどうかを判定
  475.      *
  476.      * @param Product $Product
  477.      *
  478.      * @return boolean 閲覧可能な場合はtrue
  479.      */
  480.     protected function checkVisibility(Product $Product)
  481.     {
  482.         $is_admin $this->session->has('_security_admin');
  483.         // 管理ユーザの場合はステータスやオプションにかかわらず閲覧可能.
  484.         if (!$is_admin) {
  485.             // 在庫なし商品の非表示オプションが有効な場合.
  486.             // if ($this->BaseInfo->isOptionNostockHidden()) {
  487.             //     if (!$Product->getStockFind()) {
  488.             //         return false;
  489.             //     }
  490.             // }
  491.             // 公開ステータスでない商品は表示しない.
  492.             if ($Product->getStatus()->getId() !== ProductStatus::DISPLAY_SHOW) {
  493.                 return false;
  494.             }
  495.         }
  496.         return true;
  497.     }
  498. }