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

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