src/AppBundle/Controller/Admin/Base/FacilityArticleBaseController.php line 23

Open in your IDE?
  1. <?php
  2. namespace AppBundle\Controller\Admin\Base;
  3. use AppBundle\Doctrine\Filter\PostTypeFilter;
  4. use AppBundle\Service\ContentManager;
  5. use Doctrine\ORM\EntityManager;
  6. use Doctrine\ORM\Query\FilterCollection;
  7. use Symfony\Component\HttpFoundation\RedirectResponse;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Symfony\Component\HttpFoundation\Response;
  10. use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
  11. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  12. use Symfony\Component\HttpFoundation\JsonResponse;
  13. use Symfony\Component\DependencyInjection\Container;
  14. use AppBundle\Component\PageBuilder\PageBuilder;
  15. use Doctrine\ORM\EntityNotFoundException;
  16. use AppBundle\Controller\Admin\Base\FacilityBaseController;
  17. use Symfony\Component\Form\Extension\Core\Type;
  18. use AppBundle\Entity\Master\Facility;
  19. class FacilityArticleBaseController extends FacilityBaseController
  20. {
  21.     protected function buildSearchForm($data = [], $params = [])
  22.     {
  23.         $settings $this->entity_settings;
  24.         $form parent::buildSearchForm($data$params);
  25.         if($settings->get('relations.category')){
  26.             $category_class $this->models['category'];
  27.             $repo $this->getDoctrine()->getRepository($category_class);
  28.             $criteria = [];
  29.             if ($this->entity_settings->isMultilingual()) {
  30.                 $criteria['language_alias'] = $this->container->getParameter('language.default''jp');
  31.             }
  32.             $categories $repo->findBy($criteria, ['sort_num' => 'ASC''id' => 'ASC']);
  33.             $categoryList = [];
  34.             foreach($categories as $category){
  35.                 $categoryList[$category->getTitle()] = $category->getId();
  36.             }
  37.             $form->add('category'Type\ChoiceType::class, [
  38.                 'required' => false,
  39.                 'label' => 'カテゴリー:',
  40.                 'choices' => $categoryList,
  41.                 'placeholder' => '(指定なし)',
  42.                 'attr' => [
  43.                     'class' => 'form-control form-control-inline'
  44.                 ],
  45.                 'label_attr' => [
  46.                     'class' => null
  47.                 ]
  48.             ]);
  49.         }
  50.         return $form;
  51.     }
  52.     /**
  53.      * @param FilterControllerEvent $event
  54.      * @throws EntityNotFoundException
  55.      */
  56.     public function before(FilterControllerEvent $event)
  57.     {
  58.         parent::before($event);
  59.     }
  60.     /**
  61.      * @param string $action
  62.      * @param FilterControllerEvent $event
  63.      * @throws NotFoundHttpException
  64.      */
  65.     protected function beforeActionCheck($actionFilterControllerEvent $event)
  66.     {
  67.         parent::beforeActionCheck($action$event);
  68.         $settings $this->entity_settings;
  69.         // 各アクションの before メソッドが存在すれば実行する
  70.         switch ($action) {
  71.             case 'previewAction':
  72.                 if (!$settings->get('actions.preview')) {
  73.                     throw new NotFoundHttpException();
  74.                 }
  75.                 if (method_exists($this'beforePreviewAction')) {
  76.                     $this->beforePreviewAction($event);
  77.                 }
  78.                 break;
  79.         }
  80.     }
  81.     /**
  82.      * 施設を取得する
  83.      *
  84.      * @param $code
  85.      * @return null|object
  86.      */
  87.     protected function getFacilityByCode($code)
  88.     {
  89.         if (!empty($this->facility)) {
  90.             return $this->facility;
  91.         } else {
  92.             $repo $this->getDoctrine()->getRepository(Facility::class);
  93.             return $repo->findOneBy(['code' => $code]);
  94.         }
  95.     }
  96.     /**
  97.      * 施設のホームページを取得
  98.      *
  99.      * @param $code
  100.      * @return string
  101.      */
  102.     protected function getFacilityHomeUrl($code)
  103.     {
  104.         $facility $this->getFacilityByCode($code);
  105.         if ($facility) {
  106.             $website $this->facility->getWebsite();
  107.             if(empty($website)){
  108.                 return rtrim(CMS__WEB_ROOT_PATH'/') . '/' $code;
  109.             } else {
  110.                 return rtrim($this->facility->getWebsite(), '/');
  111.             }
  112.         } else {
  113.             false;
  114.         }
  115.     }
  116.     /**
  117.      * 施設に応じて入力項目を変更する
  118.      *
  119.      * @param $builder
  120.      * @param $facility_code
  121.      * @param $entity
  122.      */
  123.     protected function initForm($builder$facility_code$entity null)
  124.     {
  125.     }
  126.     /**
  127.      * 保存前の値を編集する
  128.      *
  129.      * @param $formData
  130.      * @param $mode
  131.      * @return mixed
  132.      */
  133.     protected function filterFormData($formData$mode)
  134.     {
  135.         return $formData;
  136.     }
  137.     /**
  138.      * @param $facility
  139.      * @param $id
  140.      * @param array $params
  141.      * @return string | null
  142.      */
  143.     protected function getPreviewPageUrl($facility$id$params=[])
  144.     {
  145.         if ($this->entity_settings->get('actions.preview')) {
  146.             return $this->get('router')->generate($this->routes['preview'], $params);
  147.         } else {
  148.             return null;
  149.         }
  150.     }
  151.     /**
  152.      * @param Request $request
  153.      * @param $facility
  154.      * @param $id
  155.      * @return Response
  156.      */
  157.     public function previewAction(Request $request$facility$id)
  158.     {
  159.         if ($this->container->has('profiler'))
  160.         {
  161.             $this->container->get('profiler')->disable();
  162.         }
  163.         $em $this->getDoctrine()->getManager();
  164.         /** @var FilterCollection $filters */
  165.         $filters $em->getFilters();
  166.         if($filters->isEnabled('post_type')){
  167.             /** @var PostTypeFilter $filter */
  168.             $filter $filters->getFilter('post_type');
  169.             $filter->disableForEntity($this->models['item']);
  170.         }
  171.         $repo $this->getDoctrine()->getRepository($this->models['item']);
  172.         $comparisonId $request->query->get('comparison');
  173.         $entry $repo->findOneBy(['id' => $id]);
  174.         if(!$entry){
  175.             throw $this->createNotFoundException();
  176.         }
  177.         if($comparisonId){
  178.             $comparison $repo->findOneBy(['id' => $comparisonId]);
  179.         } elseif(method_exists($repo'findMasterEntity')){
  180.             $master $repo->findMasterEntity($entry);
  181.             if($master && $master->getId() === $entry->getId()){
  182.                 $comparison null;
  183.             } else {
  184.                 $comparison $master;
  185.             }
  186.         } else {
  187.             $comparison null;
  188.         }
  189.         if($comparison) {
  190.             $params1 $this->generatePreviewParams($comparison);
  191.             $preview1 $this->getPreviewPageUrl($facility$comparison->getId(), $params1);
  192.         } else {
  193.             $preview1 null;
  194.         }
  195.         $params2 $this->generatePreviewParams($entry);
  196.         $preview2 $this->getPreviewPageUrl($facility$entry->getId(), $params2);
  197.         /** @var ContentManager $manager */
  198.         $manager $this->get('app.content_manager');
  199.         $diffHighlight $this->entity_settings->get('diff_highlight'false);
  200.         if($diffHighlight && $comparison) {
  201.             $diff $manager->blockDiff($this->form_class$entry$comparison, [
  202.                 'entity_settings' => $this->entity_settings
  203.             ]);
  204.         } else {
  205.             $diff = [];
  206.         }
  207.         return $this->render('::admin/controller-templates/diff.html.php', [
  208.             'entry' => $entry,
  209.             'comparison' => $comparison,
  210.             'preview1' => $preview1,
  211.             'preview2' => $preview2,
  212.             'diff' => $diff,
  213.         ]);
  214.     }
  215.     /**
  216.      *
  217.      * @param Request $request
  218.      * @param $id
  219.      * @return JsonResponse
  220.      * @throws NotFoundHttpException
  221.      */
  222.     public function autoSaveAction(Request $request$id)
  223.     {
  224.         $em $this->getDoctrine()->getManager();
  225.         $filters $em->getFilters();
  226.         if ($filters->isEnabled('post_type')) {
  227.             $filters->disable('post_type');
  228.         }
  229.         $entity $this->findEntity($id);
  230.         $repo $this->getDoctrine()->getRepository($this->models['item']);
  231.         if (!$entity) {
  232.             throw new NotFoundHttpException();
  233.         }
  234.         $builder $this->createPageBuilder($this->form_class$entity);
  235.         try {
  236.             $violations $builder->handleRequest($request);
  237.             $formData $builder->getData();
  238.             if (property_exists($entity'slug') && $entity->slug == '' && empty($formData['slug'])) {
  239.                 $formData['slug'] = $this->generateUniqueId();
  240.             }
  241.             // ドラフトの作成
  242.             $revisions $repo->findAllRevisions($id'draft');
  243.             if ($revisions) {
  244.                 $revision $revisions[0];
  245.             } else {
  246.                 //$revision = $this->duplicateEntity($entity);
  247.                 $revision = clone $entity;
  248.                 $revision->setRevisionParent($entity->getId());
  249.                 $revision->setPostType('draft');
  250.                 $em->persist($revision);
  251.             }
  252.             $revision->bindFormData($formData);
  253.             $em->flush();
  254.         } catch (\Exception $ex) {
  255.             return new JsonResponse([
  256.                 'status' => 'failed',
  257.                 'message' => $ex->getMessage(),
  258.                 'trace' => $ex->getTraceAsString()
  259.             ]);
  260.         }
  261.         return new JsonResponse([
  262.             'status' => 'done'
  263.         ]);
  264.     }
  265.     /**
  266.      *
  267.      * @return array
  268.      */
  269.     protected function getDatatableColumns()
  270.     {
  271.         $columns = [];
  272.         $settings $this->entity_settings;
  273.         if($settings->get('relations.category')){
  274.             $columns[] = [
  275.                 "sTitle" => "カテゴリ",
  276.                 "width" => "130px",
  277.                 "mData" => "category",
  278.                 "@render" => "function(data, type, row) {
  279.                     if(null !== data && 'undefined' !== typeof data.title){
  280.                         return data.title;
  281.                     } else {
  282.                         return '(なし)';
  283.                     }
  284.                 }"
  285.             ];
  286.         }
  287.         if($settings->get('relations.tag')){
  288.             $columns[] = [
  289.                 "sTitle" => "タグ",
  290.                 "width" => "130px",
  291.                 "mData" => "tags",
  292.                 "sortable" => false,
  293.                 "@render" => "function(data, type, row) {
  294.                     if(data.length == 0){
  295.                         return 'なし';
  296.                     } else {
  297.                         var data_list = [];
  298.                         for (var i=0; i < data.length; i++ ){
  299.                             data_list.push(data[i]['title']);
  300.                         }
  301.                         return data_list.join('<br>');
  302.                     }
  303.                 }"
  304.             ];
  305.         }
  306.         $columns[] = [
  307.             "sTitle" => "タイトル",
  308.             "mData" => "title",
  309.             "@render" => "function(data, type, row){
  310.                 return ('' == data) ? '<strong>(無題)</strong>':'<strong>' + data + '</strong>';
  311.             }"
  312.         ];
  313.         return $columns;
  314.     }
  315.     protected function getDefaultOrderBy()
  316.     {
  317.         return ['sort_num' => 'asc''id' => 'desc'];
  318.     }
  319.     protected function baseMeta($mode$meta = [], $id null)
  320.     {
  321.         $facility $this->facility;
  322.         switch ($mode) {
  323.             case "TOP":
  324.             case "INDEX":
  325.                 $meta["page"]["title"] = $meta["base"]["title"] . " | 一覧";
  326.                 $meta["page"]["path"] = $meta["base"]["path"];
  327.                 $meta["breadcrumbs"]["current"]["title"] = $meta["base"]["title"];
  328.                 $meta["breadcrumbs"]["parent"]["title"] = "TOP";
  329.                 $meta["breadcrumbs"]["parent"]["path"] = "/admin/";
  330.                 break;
  331.             case "NEW":
  332.                 $meta["page"]["title"] = $meta["base"]["title"] . " | 新規作成";
  333.                 $meta["page"]["path"] = $meta["base"]["path"] . "new/";
  334.                 $meta["breadcrumbs"]["current"]["title"] = "新規作成";
  335.                 $meta["breadcrumbs"]["parent"]["title"] = $meta["base"]["title"];
  336.                 $meta["breadcrumbs"]["parent"]["path"] = $meta["base"]["path"];
  337.                 break;
  338.             case "DETAIL":
  339.                 $meta["page"]["title"] = $meta["base"]["title"] . " | 詳細";
  340.                 $meta["page"]["path"] = $meta["base"]["path"] . $id '/';
  341.                 $meta["breadcrumbs"]["current"]["title"] = "詳細";
  342.                 $meta["breadcrumbs"]["parent"]["title"] = $meta["base"]["title"];
  343.                 $meta["breadcrumbs"]["parent"]["path"] = $meta["base"]["path"];
  344.                 break;
  345.             case "EDIT":
  346.                 $meta["page"]["title"] = $meta["base"]["title"] . " | 編集";
  347.                 $meta["page"]["path"] = $meta["base"]["path"] . $id '/edit/';
  348.                 $meta["breadcrumbs"]["current"]["title"] = "編集";
  349.                 $meta["breadcrumbs"]["parent"]["title"] = $meta["base"]["title"];
  350.                 $meta["breadcrumbs"]["parent"]["path"] = $meta["base"]["path"];
  351.                 break;
  352.             case "IMPORT":
  353.                 $meta["page"]["title"] = $meta["base"]["title"] . " | インポート";
  354.                 $meta["page"]["path"] = $meta["base"]["path"] . "import/";
  355.                 $meta["breadcrumbs"]["current"]["title"] = "インポート";
  356.                 $meta["breadcrumbs"]["parent"]["title"] = $meta["base"]["title"];
  357.                 $meta["breadcrumbs"]["parent"]["path"] = $meta["base"]["path"];
  358.                 break;
  359.             default:
  360.                 $meta["page"]["title"] = "[Unknown]";
  361.                 $meta["page"]["path"] = "/unknown";
  362.                 $meta["breadcrumbs"]["current"]["title"] = "[Unknown]";
  363.                 $meta["breadcrumbs"]["parent"]["title"] = "[Unknown]";
  364.                 $meta["breadcrumbs"]["parent"]["path"] = "/unknown";
  365.         }
  366.         return $meta;
  367.     }
  368.     /**
  369.      * @param Request $request
  370.      * @return RedirectResponse|Response
  371.      */
  372.     public function importAction(Request $request)
  373.     {
  374.         set_time_limit(0);
  375.         $meta $this->meta('IMPORT');
  376.         $builder $this->createPageBuilder(AdminImportForm::class, null);
  377.         if ($request->isMethod('post')) {
  378.             // ファイル取得
  379.             $file $request->files->get("__block_file")["file"];
  380.             $import $this->get("app.helper.import_helper");
  381.             $params $request->request->all();
  382.             $formatData $import->getFormatData($params$file);
  383.             $isDelete = (boolean)$params["__block_is_delete"]["value"];
  384.             if (!empty($formatData) && method_exists($this"importExecuting")) {
  385.                 $this->importExecuting($formatData$isDelete);
  386.                 return $this->redirectToRoute($meta["redirect"], ["facility" => $this->facility->getCode()]);
  387.             }
  388.         }
  389.         return $this->render(rtrim($this->templateDirectory) . '/' 'import.html.php', [
  390.             'meta' => $meta,
  391.             'builder' => $builder
  392.         ]);
  393.     }
  394.     protected function importExecuting($formatData$isDelete)
  395.     {
  396.         $import $this->get("app.helper.import_helper");
  397.         $em $this->getDoctrine()->getManager();
  398.         $entity = new $this->models['item']();
  399.         foreach ($formatData as $format) {
  400.             $data = [];
  401.             $publicDate = new \DateTime($format["post_date"]);
  402.             $data["status"] = $format["status"];
  403.             $data["public_date"] = $publicDate;
  404.             $data["publish_at"] = $publicDate;
  405.             $data["title"] = $format["title"];
  406.             $data["post_type"] = "master";
  407.             // カテゴリ
  408.             if (!empty($format["category"])) {
  409.                 $category = [];
  410.                 $category["title"] = $format["category"];
  411.                 $data["category"] = $this->getCategoryIdForImport(
  412.                     $this->models['category'], $category
  413.                 );
  414.             }
  415.             // サブカテゴリ
  416.             if (!empty($format["sub_category"])) {
  417.                 $category = [];
  418.                 $category["title"] = $format["sub_category"];
  419.                 $category["main_category"] = $data["category"];
  420.                 $data["sub_category"] = $this->getCategoryIdForImport(
  421.                     $this->models['subcategory'], $category
  422.                 );
  423.             }
  424.             // タグ
  425.             if (!empty($format["tags"])) {
  426.                 $tags explode(","$format["tags"]);
  427.                 foreach ($tags as $v) {
  428.                     $tag = [];
  429.                     $tag["name"] = $v;
  430.                     $tag["alias"] = $this->generateUniqueId();
  431.                     $data["tags"][] = $this->getCategoryIdForImport(
  432.                         $this->models['tag'], $tag"name"
  433.                     );
  434.                 }
  435.             }
  436.             $data["detail_type"] = "article";
  437.             // カスタムブロック
  438.             $data["customblock"] = ["visual1__" $this->generateUniqueId() => [
  439.                 "values" => $import->importFile($format["contents"]),
  440.                 "is_active" => true
  441.             ]];
  442.             $entity->bindFormData($data);
  443.             $em->persist($entity);
  444.             $em->flush();
  445.             $em->clear();
  446.         }
  447.         return true;
  448.     }
  449.     /**
  450.      * @param $entity_class
  451.      * @param $data
  452.      * @param string $value_name
  453.      * @return mixed
  454.      */
  455.     protected function getCategoryIdForImport($entity_class$data$value_name "title")
  456.     {
  457.         $repository $this->getDoctrine()->getRepository($entity_class);
  458.         $entries $repository->findBy(["{$value_name}=> $data[$value_name], "facility" => $this->facility->getId()]);
  459.         if (!empty($entries)) {
  460.             return $entries[0];
  461.         } else {
  462.             // 新規登録
  463.             $em $this->getDoctrine()->getManager();
  464.             $entity = new $entity_class();
  465.             $entity->setFacility($this->facility);
  466.             $entity->bindFormData($data);
  467.             $em->persist($entity);
  468.             $em->flush();
  469.             return $entity;
  470.         }
  471.     }
  472. }