app/Plugin/tbsFeaturePage/Controller/Admin/FeatureController.php line 284

Open in your IDE?
  1. <?php
  2. namespace Plugin\tbsFeaturePage\Controller\Admin;
  3. use Eccube\Application;
  4. use Eccube\Common\Constant;
  5. use Eccube\Controller\AbstractController;
  6. use Eccube\Form\Type\Admin\SearchProductType;
  7. use Eccube\Repository\ProductRepository;
  8. use Eccube\Util\CacheUtil;
  9. use Knp\Component\Pager\PaginatorInterface;
  10. use Plugin\tbsFeaturePage\Entity\Feature;
  11. use Plugin\tbsFeaturePage\Entity\FeatureProduct;
  12. use Plugin\tbsFeaturePage\Entity\FeatureStatus;
  13. use Plugin\tbsFeaturePage\Form\Type\Admin\FeatureType;
  14. use Plugin\tbsFeaturePage\Repository\FeatureProductRepository;
  15. use Plugin\tbsFeaturePage\Repository\FeatureRepository;
  16. use Plugin\tbsFeaturePage\Repository\FeatureStatusRepository;
  17. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
  18. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  19. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  20. use Symfony\Component\Filesystem\Filesystem;
  21. use Symfony\Component\HttpFoundation\File\File;
  22. use Symfony\Component\HttpFoundation\JsonResponse;
  23. use Symfony\Component\HttpFoundation\Request;
  24. use Symfony\Component\HttpFoundation\Response;
  25. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  26. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  27. use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
  28. use Symfony\Component\Routing\RouterInterface;
  29. class FeatureController extends AbstractController
  30. {
  31.     /** @var ProductRepository */
  32.     protected $productRepository;
  33.     /** @var FeatureRepository */
  34.     private $featureRepository;
  35.     /** @var FeatureStatusRepository */
  36.     private $featureStatusRepository;
  37.     /** @var FeatureProductRepository */
  38.     private $featureProductRepository;
  39.     /**
  40.      * FeatureController constructor.
  41.      *
  42.      * @param ProductRepository $productRepository
  43.      * @param FeatureRepository $featureRepository
  44.      * @param FeatureStatusRepository $featureStatusRepository
  45.      * @param FeatureProductRepository $featureProductRepository
  46.      */
  47.     public function __construct(
  48.         ProductRepository $productRepository,
  49.         FeatureRepository $featureRepository,
  50.         FeatureStatusRepository $featureStatusRepository,
  51.         FeatureProductRepository $featureProductRepository
  52.     ) {
  53.         $this->productRepository = $productRepository;
  54.         $this->featureRepository = $featureRepository;
  55.         $this->featureStatusRepository = $featureStatusRepository;
  56.         $this->featureProductRepository = $featureProductRepository;
  57.     }
  58.     /**
  59.      * 管理.
  60.      *
  61.      * @Route("%eccube_admin_route%/tbs_feature_page/", name="tbs_feature_page_admin_feature")
  62.      * @Template("@tbsFeaturePage/admin/index.twig")
  63.      *
  64.      * @return array|RedirectResponse
  65.      */
  66.     public function index()
  67.     {
  68.         $Features = $this->featureRepository->findBy(array(), array('rank' => 'DESC'));
  69.         return [
  70.             'Features' => $Features,
  71.         ];
  72.     }
  73.     /**
  74.      * 登録・編集.
  75.      *
  76.      * @Route("%eccube_admin_route%/tbs_feature_page/new", name="tbs_feature_page_admin_feature_new")
  77.      * @Route("%eccube_admin_route%/tbs_feature_page/{id}/edit", name="tbs_feature_page_admin_feature_edit", requirements={"id"="\d+"}, defaults={"id"=null})
  78.      * @Template("@tbsFeaturePage/admin/edit.twig")
  79.      *
  80.      * @param Request $request
  81.      * @param $id
  82.      *
  83.      * @return array|RedirectResponse
  84.      */
  85.     public function edit(Request $request, RouterInterface $router, CacheUtil $cacheUtil, $id = null)
  86.     {
  87.         $Feature = null;
  88.         $arrFeatureProducts = array('1' => null, '2' => null, '3' => null, '4' => null, '5' => null);
  89.         if (is_null($id)) {
  90.             $rank = 1;
  91.             $Feature = $this->featureRepository->findOneBy(array(), array('rank' => 'DESC'));
  92.             if ($Feature) {
  93.                 $rank = $Feature->getRank() + 1;
  94.             }
  95.             $Feature = new Feature();
  96.             $Feature
  97.                 ->setRank($rank)
  98.                 ->setStatus($this->featureStatusRepository->find(FeatureStatus::HIDE));
  99.         } else {
  100.             $Feature = $this->featureRepository->find(array('id' => $id));
  101.             if (!$Feature) {
  102.                 throw new NotFoundHttpException();
  103.             }
  104.             $FeatureProducts = $this->featureProductRepository->findBy(array('Feature' => $Feature), array('rank' => 'DESC'));
  105.             foreach ($FeatureProducts as $FeatureProduct) {
  106.                 $arrFeatureProducts[$FeatureProduct->getPosition()][] = $FeatureProduct;
  107.             }
  108.         }
  109.         $form = $this->createForm(FeatureType::class, $Feature);
  110.         if ('POST' === $request->getMethod()) {
  111.             $form->handleRequest($request);
  112.             // 登録ボタン押下
  113.             switch ($request->get('mode')) {
  114.                 case 'register':
  115.                     if ($form->isSubmitted() && $form->isValid()) {
  116.                         $Feature = $form->getData();
  117.                         // ファイルアップロード
  118.                         $file = $form['banner_file_name']->getData();
  119.                         $fs = new Filesystem();
  120.                         if ($file && $fs->exists($this->eccubeConfig['eccube_temp_image_dir'] . '/' . $file)) {
  121.                             $fs->rename(
  122.                                 $this->eccubeConfig['eccube_temp_image_dir'] . '/' . $file,
  123.                                 $this->eccubeConfig['plugin_html_realdir'] . 'tbsFeaturePage/save_image/' . $file
  124.                             );
  125.                         }
  126.                         $Feature->setUpdateDate(new \DateTime());
  127.                         $this->entityManager->persist($Feature);
  128.                         $this->entityManager->flush();
  129.                         log_info('Feature page edit ID:' . $Feature->getId());
  130.                         $this->addSuccess('tbs_feature_page.admin.save.complete', 'admin');
  131.                         if ($returnLink = $form['return_link']->getData()) {
  132.                             try {
  133.                                 // $returnLinkはpathの形式で渡される. pathが存在するかをルータでチェックする.
  134.                                 $pattern = '/^'.preg_quote($request->getBasePath(), '/').'/';
  135.                                 $returnLink = preg_replace($pattern, '', $returnLink);
  136.                                 $result = $router->match($returnLink);
  137.                                 // パラメータのみ抽出
  138.                                 $params = array_filter($result, function ($key) {
  139.                                     return 0 !== \strpos($key, '_');
  140.                                 }, ARRAY_FILTER_USE_KEY);
  141.                                 // pathからurlを再構築してリダイレクト.
  142.                                 return $this->redirectToRoute($result['_route'], $params);
  143.                             } catch (\Exception $e) {
  144.                                 // マッチしない場合はログ出力してスキップ.
  145.                                 log_warning('URLの形式が不正です。');
  146.                             }
  147.                         }
  148.                         $cacheUtil->clearDoctrineCache();
  149.                         return $this->redirectToRoute(
  150.                             'tbs_feature_page_admin_feature_edit',
  151.                             ['id' => $Feature->getId()]
  152.                         );
  153.                     } else {
  154.                         $this->addError('tbs_feature_page.admin.save.error', 'admin');
  155.                     }
  156.                     break;
  157.                 default:
  158.                     break;
  159.             }
  160.         }
  161.         // 商品検索フォーム
  162.         $builder = $this->formFactory
  163.             ->createBuilder(SearchProductType::class);
  164.         $searchProductModalForm = $builder->getForm();
  165.         return [
  166.             'form' => $form->createView(),
  167.             'Feature' => $Feature,
  168.             'FeatureProducts' => $arrFeatureProducts,
  169.             'searchProductModalForm' => $searchProductModalForm->createView(),
  170.             'id' => $id,
  171.         ];
  172.     }
  173.     /**
  174.      * 削除.
  175.      *
  176.      * @Method("DELETE")
  177.      * @Route("%eccube_admin_route%/tbs_feature_page/{id}/delete", name="tbs_feature_page_admin_feature_delete")
  178.      *
  179.      * @param Feature $Feature
  180.      *
  181.      * @return RedirectResponse
  182.      */
  183.     public function delete(Feature $Feature)
  184.     {
  185.         $this->isTokenValid();
  186.         $this->entityManager->remove($Feature);
  187.         $this->entityManager->flush($Feature);
  188.         $this->addSuccess('tbs_feature_page.admin.delete.complete', 'admin');
  189.         log_info('Feature page delete', ['id' => $Feature->getId()]);
  190.         return $this->redirect($this->generateUrl('tbs_feature_page_admin_feature'));
  191.     }
  192.     /**
  193.      * @Route("/%eccube_admin_route%/tbs_feature_page/{url}/display", name="tbs_feature_page_admin_feature_display")
  194.      */
  195.     public function display(Request $request, $url = null)
  196.     {
  197.         if (!is_null($url)) {
  198.             return $this->redirectToRoute('feature_detail', ['url' => $url, 'admin' => '1']);
  199.         }
  200.         return $this->redirectToRoute(
  201.             'tbs_feature_page_admin_feature'
  202.         );
  203.     }
  204.     /**
  205.      * @Route("/%eccube_admin_route%/tbs_feature_page/image/add", name="tbs_feature_page_admin_feature_image_add", methods={"POST"})
  206.      */
  207.     public function addImage(Request $request)
  208.     {
  209.         if (!$request->isXmlHttpRequest()) {
  210.             throw new BadRequestHttpException();
  211.         }
  212.         $images = $request->files->get('feature');
  213.         $allowExtensions = ['gif', 'jpg', 'jpeg', 'png'];
  214.         $filename = null;
  215.         if (isset($images['banner_file'])) {
  216.             $image = $images['banner_file'];
  217.             //ファイルフォーマット検証
  218.             $mimeType = $image->getMimeType();
  219.             if (0 !== strpos($mimeType, 'image')) {
  220.                 throw new UnsupportedMediaTypeHttpException();
  221.             }
  222.             // 拡張子
  223.             $extension = $image->getClientOriginalExtension();
  224.             if (!in_array($extension, $allowExtensions)) {
  225.                 throw new UnsupportedMediaTypeHttpException();
  226.             }
  227.             $filename = date('mdHis') . uniqid('_') . '.' . $extension;
  228.             $image->move($this->eccubeConfig['eccube_temp_image_dir'], $filename);
  229.         }
  230.         return $this->json(['filename' => $filename], 200);
  231.     }
  232.     /**
  233.      * @Route(
  234.      *     "/%eccube_admin_route%/tbs_feature_page/search/product/{page_no}",
  235.      *     requirements={"page_no" = "\d+"},
  236.      *     defaults={"page_no" = 1},
  237.      *     name="tbs_feature_page_admin_feature_search_product"
  238.      * )
  239.      * @Template("@tbsFeaturePage/admin/search_product.twig")
  240.      */
  241.     public function searchProduct(Request $request, int $page_no = 1, PaginatorInterface $paginator)
  242.     {
  243.         if ($request->isXmlHttpRequest() && $this->isTokenValid()) {
  244.             log_debug('search product start.');
  245.             $page_count = $this->eccubeConfig['eccube_default_page_count'];
  246.             $session = $this->session;
  247.             if ('POST' === $request->getMethod()) {
  248.                 $page_no = 1;
  249.                 $searchData = array(
  250.                     'id' => $request->get('id'),
  251.                 );
  252.                 if ($categoryId = $request->get('category_id')) {
  253.                     $Category = $this->categoryRepository->find($categoryId);
  254.                     $searchData['category_id'] = $Category;
  255.                 }
  256.                 $session->set('eccube.admin.feature.product.search', $searchData);
  257.                 $session->set('eccube.admin.feature.product.search.page_no', $page_no);
  258.             } else {
  259.                 $searchData = (array)$session->get('eccube.admin.feature.product.search');
  260.                 if (is_null($page_no)) {
  261.                     $page_no = intval($session->get('eccube.admin.feature.product.search.page_no'));
  262.                 } else {
  263.                     $session->set('eccube.admin.feature.product.search.page_no', $page_no);
  264.                 }
  265.             }
  266.             $qb = $this->productRepository
  267.                 ->getQueryBuilderBySearchDataForAdmin($searchData);
  268.             /** @var \Knp\Component\Pager\Pagination\SlidingPagination $pagination */
  269.             $pagination = $paginator->paginate(
  270.                 $qb,
  271.                 $page_no,
  272.                 $page_count,
  273.                 ['wrap-queries' => true]
  274.             );
  275.             /** @var $Products \Eccube\Entity\Product[] */
  276.             $Products = $pagination->getItems();
  277.             if (empty($Products)) {
  278.                 log_debug('search product not found.');
  279.             }
  280.             return [
  281.                 'Products' => $Products,
  282.                 'pagination' => $pagination,
  283.             ];
  284.         }
  285.     }
  286.     /**
  287.      * @Route("/%eccube_admin_route%/tbs_feature_page/product/register", name="tbs_feature_page_admin_feature_product_register")
  288.      *
  289.      * @return JsonResponse
  290.      */
  291.     public function registerProduct(Request $request)
  292.     {
  293.         if (!$request->isXmlHttpRequest()) {
  294.             throw new BadRequestHttpException();
  295.         }
  296.         $productIds = $request->get('productIds');
  297.         $featureId = $request->get('featureId');
  298.         $Feature = $this->featureRepository->find($featureId);
  299.         $position = $request->get('position');
  300.         foreach ($productIds as $productId) {
  301.             $rank = 1;
  302.             $FeatureProduct = $this->featureProductRepository->findOneBy(array(
  303.                     'Feature' => $Feature,
  304.                     'position' => $position
  305.                 ), array('rank' => 'DESC'));
  306.             if ($FeatureProduct) {
  307.                 $rank = $FeatureProduct->getRank() + 1;
  308.             }
  309.             $Product = $this->productRepository->find($productId);
  310.             $FeatureProduct = new FeatureProduct();
  311.             $FeatureProduct
  312.                 ->setRank($rank)
  313.                 ->setProduct($Product)
  314.                 ->setFeature($Feature)
  315.                 ->setPosition($position);
  316.             $this->entityManager->persist($FeatureProduct);
  317.             $this->entityManager->flush($FeatureProduct);
  318.         }
  319.         $this->addSuccess('admin.common.save_complete', 'admin');
  320.         return $this->json(['success' => true]);
  321.     }
  322.     /**
  323.      * @Route("/%eccube_admin_route%/tbs_feature_page/product/{id}/delete", requirements={"id" = "\d+"}, name="tbs_feature_page_admin_feature_product_delete", methods={"DELETE"})
  324.      */
  325.     public function deleteProduct(Request $request, $id, CacheUtil $cacheUtil)
  326.     {
  327.         $this->isTokenValid();
  328.         $FeatureProduct = $this->featureProductRepository->find($id);
  329.         if (!$FeatureProduct) {
  330.             $this->deleteMessage();
  331.             return $this->redirectToRoute('tbs_feature_page_admin_feature_edit', ['id' => $feature_id]);
  332.         }
  333.         $feature_id = $FeatureProduct->getFeature()->getId();
  334.         $this->entityManager->remove($FeatureProduct);
  335.         $this->entityManager->flush($FeatureProduct);
  336.         $this->addSuccess('tbs_feature_page.admin.feature_edit.product_delete.complete', 'admin');
  337.         $cacheUtil->clearDoctrineCache();
  338.         return $this->redirectToRoute('tbs_feature_page_admin_feature_edit', ['id' => $feature_id]);
  339.     }
  340.     /**
  341.      * @Route("/%eccube_admin_route%/tbs_feature_page/move", name="tbs_feature_page_admin_feature_move", methods={"POST"})
  342.      */
  343.     public function moveRank(Request $request, CacheUtil $cacheUtil)
  344.     {
  345.         if (!$request->isXmlHttpRequest()) {
  346.             throw new BadRequestHttpException();
  347.         }
  348.         if ($this->isTokenValid()) {
  349.             $ranks = $request->request->all();
  350.             foreach ($ranks as $featureId => $rank) {
  351.                 $Feature = $this->featureRepository->find($featureId);
  352.                 $Feature->setRank($rank);
  353.                 $this->entityManager->persist($Feature);
  354.             }
  355.             $this->entityManager->flush();
  356.         }
  357.         $cacheUtil->clearDoctrineCache();
  358.         return new Response('Successful');
  359.     }
  360.     /**
  361.      * @Route("/%eccube_admin_route%/tbs_feature_page/product/move", name="tbs_feature_page_admin_feature_product_move", methods={"POST"})
  362.      */
  363.     public function moveRankProduct(Request $request, CacheUtil $cacheUtil)
  364.     {
  365.         if (!$request->isXmlHttpRequest()) {
  366.             throw new BadRequestHttpException();
  367.         }
  368.         if ($this->isTokenValid()) {
  369.             $ranks = $request->request->all();
  370.             foreach ($ranks as $id => $rank) {
  371.                 $FeatureProduct = $this->featureProductRepository->find($id);
  372.                 $FeatureProduct->setRank($rank);
  373.                 $this->entityManager->persist($FeatureProduct);
  374.             }
  375.             $this->entityManager->flush();
  376.             $cacheUtil->clearDoctrineCache();
  377.             return new Response('Successful');
  378.         }
  379.     }
  380. }