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

Open in your IDE?
  1. <?php
  2. namespace AppBundle\Controller\Admin\Base;
  3. use AppBundle\Component\PageBuilder\Event\OnCommitEvent;
  4. use AppBundle\Component\Util\ButtonSection;
  5. use AppBundle\Entity\Approval\ApprovalRequest;
  6. use AppBundle\Entity\Master\Language;
  7. use AppBundle\Event\Approval\RequestCreatedEvent;
  8. use AppBundle\Event\PageBuilderInitializedEvent;
  9. use AppBundle\Repository\ApprovalRequestRepository;
  10. use Doctrine\ORM\Query\FilterCollection;
  11. use Symfony\Component\HttpFoundation\JsonResponse;
  12. use Symfony\Component\HttpFoundation\RedirectResponse;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
  16. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  17. use Symfony\Component\DependencyInjection\Container;
  18. use AppBundle\Controller\Admin\Base\BaseController;
  19. use AppBundle\Component\PageBuilder\PageBuilder;
  20. class MasterBaseController extends BaseController
  21. {
  22.     public function before(FilterControllerEvent $event)
  23.     {
  24.         parent::before($event);
  25.     }
  26.     public function indexAction(Request $request)
  27.     {
  28.         $settings $this->entity_settings;
  29.         if ($settings->get('single')) {
  30.             $entity $this->findOneEntity($this->models['item'], ['post_type']);
  31.             $langParent = ($entity && method_exists($entity'getLanguageParent')) ? $entity->getLanguageParent() : null;
  32.             if($entity && !empty($langParent)){
  33.                 $entity $this->findOneEntity($this->models['item'], ['id' => $langParent]);
  34.             }
  35.             if ($entity) {
  36.                 return $this->redirectToRoute($this->routes['edit'], array_merge($this->base_route_params, ['id' => $entity->getId()]));
  37.             } else {
  38.                 return $this->redirectToRoute($this->routes['new'], $this->base_route_params);
  39.             }
  40.         }
  41.         $data_table_options $this->getListDataTableOptions();
  42.         $criteria $request->query->get('criteria', []);
  43.         if (isset($data_table_options['ajax']['url']) && !empty($criteria)) {
  44.             $data_table_options['ajax']['url'] = $this->appendParamsToUrl($data_table_options['ajax']['url'],
  45.                 ['criteria' => $criteria]);
  46.         }
  47.         return $this->render($this->views['index'], [
  48.             'meta' => $this->meta('INDEX'),
  49.             'data_table_options' => $data_table_options,
  50.             'button_sections' => isset($this->button_sections['index']) ? $this->button_sections['index'] : [],
  51.             'search_form' => $this->buildSearchForm([], [
  52.                 'criteria' => $criteria
  53.             ])->createView(),
  54.         ]);
  55.     }
  56.     public function jsonAction(Request $request)
  57.     {
  58.         $data = [];
  59.         $doctrine $this->getDoctrine();
  60.         $em $doctrine->getManager();
  61.         $filters $em->getFilters();
  62.         // 下書きの表示を許可
  63.         if($filters->isEnabled('post_type')){
  64.             $postTypeFilter $filters->getFilter('post_type');
  65.             $postTypeFilter->setAllowedTypes(['master''master:draft''master:unapproved''master:rejected']);
  66.         } else {
  67.             $postTypeFilter null;
  68.         }
  69.         $repository $em->getRepository($this->models['item']);
  70.         $criteria $this->base_criteria $request->query->get('criteria', []);
  71.         if ($this->entity_settings->isMultilingual()) {
  72.             // 言語フィルタ設定
  73.             if (!empty($criteria['language'])) {
  74.                 $langAlias $criteria['language'];
  75.             }
  76.             else {
  77.                 $langAlias $this->container->getParameter('language.default''jp');
  78.             }
  79.             $em $this->getDoctrine()->getManager();
  80.             $filter $em->getFilters()->enable('language');
  81.             $filter->setParameter('language'$langAlias);
  82.             unset($criteria['language']);
  83.         }
  84.         // 空の検索条件を除外
  85.         $criteria array_filter($criteria, function ($value) {
  86.             return $value !== '';
  87.         });
  88.         $columns $request->query->get('columns');
  89.         $order $request->query->get('order');
  90.         if (!empty($order)) {
  91.             $orderBy = [];
  92.             foreach ($order as $value) {
  93.                 $column $columns[$value['column']];
  94.                 // スネークケースに変換
  95.                 $field Container::underscore($column['data']);
  96.                 $orderBy[$field] = $value['dir'];
  97.             }
  98.         } else {
  99.             $orderBy $this->getDefaultOrderBy();
  100.         }
  101.         $limit $request->get("length"10);
  102.         $offset $request->get("start"0);
  103.         if (-== $limit) {
  104.             $limit $offset null;
  105.         }
  106.         $entities $repository->searchBy($criteria$orderBy$limit$offset);
  107.         foreach ($entities as $entity) {
  108.             $data[] = $entity->toArray();
  109.         }
  110.         $recordsFiltered $repository->countBy($criteria);
  111.         $recordsTotal $repository->countBy($this->base_criteria);
  112.         //レスポンス(JSONで返す)
  113.         return new JsonResponse([
  114.             'data' => $data,
  115.             'recordsFiltered' => $recordsFiltered,
  116.             'recordsTotal' => $recordsTotal,
  117.         ]);
  118.     }
  119.     public function newAction(Request $request)
  120.     {
  121.         $settings $this->entity_settings;
  122.         if ($settings->isMultilingual()) {
  123.             return $this->multiLingualNewAction($request);
  124.         }
  125.         if ($settings->get('single')) {
  126.             $entity $this->findOneEntity($this->models['item']);
  127.             $langParent = ($entity && method_exists($entity'getLanguageParent')) ? $entity->getLanguageParent() : null;
  128.             if($entity && !empty($langParent)){
  129.                 $entity $this->findOneEntity($this->models['item'], ['id' => $langParent]);
  130.             }
  131.             if ($entity) {
  132.                 return $this->redirectToRoute(
  133.                     $this->entity_settings->get('base_route') . "_edit",
  134.                     ['id' => $entity->getId()]
  135.                 );
  136.             }
  137.         }
  138.         if($this->isGranted('approval_request_edit')){
  139.             $approval_required false;
  140.         } else {
  141.             $approval_required $settings->get('approval_required'false);
  142.         }
  143.         $preview_url null;
  144.         $em $this->getDoctrine()->getManager();
  145.         $entity = new $this->models['item']();
  146.         $builder $this->createPageBuilder($this->form_classnull'new');
  147.         $this->pageBuilderOnLoad($builder);
  148.         $buttonAction $request->request->get('_button_action''default');
  149.         if ($request->isMethod('post')) {
  150.             $referer $request->headers->get('referer');
  151.             $violations $builder->handleRequest($request);
  152.             $builder->initMediaUsageTracker();
  153.             // エラーがないとき
  154.             if (empty($violations)) {
  155.                 $repo $em->getRepository($this->models['item']);
  156.                 $max = (method_exists($entity'getSortNum')) ? $repo->getMaxSortNum() : 0;
  157.                 if ($buttonAction === 'preview') {
  158.                     // プレビューの作成
  159.                     $preview $this->duplicateEntity($entity);
  160.                     $preview->setRevisionParent($entity->getId());
  161.                     $preview->setPostType('preview');
  162.                     $blocks2 array_map(function($block){
  163.                         return clone $block;
  164.                     }, $builder->getBlocks());
  165.                     $builder->setBlocks($blocks2);
  166.                     $builder->commit(OnCommitEvent::MODE_PREVIEW);
  167.                     $formData $builder->getData();
  168.                     $formData $this->filterFormData($formData'new');
  169.                     $preview->bindFormData($formData);
  170.                     $token $this->generateAccessToken();
  171.                     $preview->setAccessToken($token);
  172.                     $this->save($em$preview$formDataself::SAVE_MODE_PREVIEW);
  173.                     if($this->entity_settings->isRevisable()) {
  174.                         $previewParams = [
  175.                             'id' => $preview->getId()
  176.                         ];
  177.                         $preview_url $this->generateUrl($this->routes['preview'], array_merge($this->base_route_params$previewParams));
  178.                     } else {
  179.                         $previewParams = [
  180.                             'preview_id' => $preview->getId(),
  181.                             'cms_token' => $token,
  182.                             'cms_mode' => 'tmp_preview'
  183.                         ];
  184.                         $preview_url $this->getPreviewPageUrl($preview->getId(), $previewParams);
  185.                     }
  186.                 } else {
  187.                     $builder->commit();
  188.                     $formData $builder->getData();
  189.                     $formData $this->filterFormData($formData'new');
  190.                     $entity->bindFormData($formData);
  191.                     $post_type = ('draft' === $buttonAction) ? 'master:draft' 'master';
  192.                     if(method_exists($entity'setPostType')){
  193.                         if($approval_required && 'master' === $post_type){
  194.                             $post_type 'master:unapproved';
  195.                         }
  196.                         $entity->setPostType($post_type);
  197.                     }
  198.                     if (method_exists($entity'setSortNum')) {
  199.                         $entity->setSortNum($max 1);
  200.                     }
  201.                     if (method_exists($entity'setLanguageAlias')) {
  202.                         $default_lang = ($this->container->hasParameter('language.default')) ? $this->container->getParameter('language.default') : 'jp';
  203.                         $entity->setLanguageAlias($default_lang);
  204.                     }
  205.                     if (method_exists($entity'setLanguageActive')) {
  206.                         $entity->setLanguageActive(true);
  207.                     }
  208.                     $this->save($em$entity$formDataself::SAVE_MODE_NEW, [
  209.                         'flash_message' => $this->title MSG_NEW_END
  210.                     ]);
  211.                     $this->saveMediaUsages($entity);
  212.                     if ($this->entity_settings->isRevisable()) {
  213.                         $revision $this->generateRevision($entity);
  214.                         $revision->setPostType(('draft' === $buttonAction) ? 'draft' 'revision');
  215.                         $em->persist($revision);
  216.                         $em->flush();
  217.                         if($approval_required && $revision){
  218.                             $approval_request $this->createApprovalRequest($revisionApprovalRequest::REQUEST_TYPE_CREATE$this->getUser());
  219.                             $em->persist($approval_request);
  220.                             $em->flush();
  221.                             $this->dispatcher->dispatch(RequestCreatedEvent::NAME, new RequestCreatedEvent($approval_request));
  222.                         }
  223.                         $this->saveMediaUsages($revision);
  224.                     }
  225.                     if($settings->get('single'false)){
  226.                         return $this->redirectToRoute($this->routes['edit'], [
  227.                             'id' => $entity->getId(),
  228.                             'disable_redirect_suggestion' => true
  229.                         ]);
  230.                     } else {
  231.                         return $this->redirect($this->base_path);
  232.                     }
  233.                 }
  234.             }
  235.         }
  236.         return $this->render($this->views['edit'], [
  237.             'meta' => $this->meta('NEW'),
  238.             'builder' => $builder,
  239.             'preview_url' => $preview_url,
  240.             'redirect_url' => null,
  241.             'redirect_message' => null,
  242.             'entity' => null,
  243.             'master_entity' => null,
  244.             'post_type' => null,
  245.             'approval_required' => $approval_required,
  246.             'revisions' => [],
  247.             'revision_history' => [],
  248.             'approval_history' => [],
  249.             'button_sections' => isset($this->button_sections['new']) ? $this->button_sections['new'] : [],
  250.             '_pageBuilderParams' => $builder->getSharedParams(),
  251.             '_routes' => $this->routes,
  252.             '_base_route_params' => $this->base_route_params,
  253.         ]);
  254.     }
  255.     public function multiLingualNewAction(Request $request)
  256.     {
  257.         $facility 'master';
  258.         $translator $this->container->get('translator');
  259.         $this->get('app.helper.script_loader')
  260.             ->register('language-edit'CMS__ADMIN_PATH 'js/pages/language-edit.js');
  261.         $settings $this->entity_settings;
  262.         if($this->isGranted('approval_request_edit')){
  263.             $approval_required false;
  264.         } else {
  265.             $approval_required $settings->get('approval_required'false);
  266.         }
  267.         $languages $this->getMasterLanguages();
  268.         $em $this->getDoctrine()->getManager();
  269.         $default_lang $this->container->getParameter('language.default''jp');
  270.         $selected_languages $request->request->get('select_lang', []);
  271.         $active_language $request->request->get('_active-language'null);
  272.         $violations = [];
  273.         $languageHeading $this->getLanguagesHeading($languages);
  274.         // 言語ごとのbuilderを設定
  275.         $builders $this->createPageBuilderLanguages($languages);
  276.         $preview_url null;
  277.         $buttonAction $request->request->get('_button_action''default');
  278.         $_pageBuilderParams = [];
  279.         foreach ($builders as $builder) {
  280.             $_pageBuilderParams += $builder->getSharedParams();
  281.         }
  282.         if ($request->isMethod('post')) {
  283.             $violations $this->validateLanguages($request$builders$selected_languages$buttonAction);
  284.             // エラーなし
  285.             if (empty($violations)) {
  286.                 $parentEntity null;
  287.                 $revisionParentEntity null;
  288.                 /** @var Language $language */
  289.                 foreach ($languages as $language) {
  290.                     $alias $language->getAlias();
  291.                     $isParent $language->isParent();
  292.                     $prefix $language->getTranslateKey() . '_';
  293.                     $entity = new $this->models['item']();
  294.                     $builder $builders[$alias];
  295.                     $repo $em->getRepository($this->models['item']);
  296.                     if($buttonAction === 'preview'){
  297.                         if ($alias !== $active_language) {
  298.                             continue;
  299.                         }
  300.                         $defaults = [
  301.                             'language' => $language,
  302.                             'parentEntity' => $parentEntity,
  303.                             'alias' => $alias,
  304.                         ];
  305.                         // プレビューの作成
  306.                         $preview $this->duplicateEntity($entity);
  307.                         $preview->setRevisionParent(null);
  308.                         $preview->setPostType('preview');
  309.                         $this->setLanguageEntityDefault($preview$defaults);
  310.                         $blocks2 array_map(function($block){
  311.                             return clone $block;
  312.                         }, $builder->getBlocks());
  313.                         $builder->setBlocks($blocks2);
  314.                         $builder->commit(OnCommitEvent::MODE_PREVIEW);
  315.                         $formData $builder->getData();
  316.                         $formData $this->filterFormDataLanguage($formData'new'$prefix);
  317.                         $preview->bindFormData($formData);
  318.                         $token $this->generateAccessToken();
  319.                         $preview->setAccessToken($token);
  320.                         $this->save($em$preview$formDataself::SAVE_MODE_PREVIEW);
  321.                         if($this->entity_settings->isRevisable()){
  322.                             $previewParams = [
  323.                                 'id' => $preview->getId()
  324.                             ];
  325.                             $preview_url $this->generateUrl($this->routes['preview'], array_merge($this->base_route_params$previewParams));
  326.                         } else {
  327.                             $previewParams = [
  328.                                 'preview_id' => $preview->getId(),
  329.                                 'cms_token' => $token,
  330.                                 'cms_mode' => 'tmp_preview',
  331.                                 '_locale' => $preview->getLanguageAlias()
  332.                             ];
  333.                             $preview_url $this->getPreviewPageUrl($facility$preview->getId(), $previewParams);
  334.                         }
  335.                     } else {
  336.                         $builder->commit();
  337.                         $formData $builder->getData();
  338.                         $formData $this->filterFormDataLanguage($formData'new'$prefix);
  339.                         // 項目がない場合は日本語の入力値をセットする
  340.                         if ($parentEntity) {
  341.                             $this->setEntityParentLanguage($entity$parentEntity$this->form_class);
  342.                         }
  343.                         $entity->bindFormData($formData);
  344.                         $post_type = ('draft' === $buttonAction) ? 'master:draft' 'master';
  345.                         $max = (method_exists($entity'getSortNum')) ? $repo->getMaxSortNumForLanguage($language$isParent) : 0;
  346.                         $defaults = [
  347.                             'max' => $max,
  348.                             'buttonAction' => $buttonAction,
  349.                             'language' => $language,
  350.                             'parentEntity' => $parentEntity,
  351.                             'alias' => $alias,
  352.                             'selected_languages' => $selected_languages
  353.                         ];
  354.                         $this->setLanguageEntityDefault($entity$defaults);
  355.                         if(method_exists($entity'setPostType')){
  356.                             if($approval_required && 'master' === $post_type){
  357.                                 $post_type 'master:unapproved';
  358.                             }
  359.                             $entity->setPostType($post_type);
  360.                         }
  361.                         $this->save($em$entity$formDataself::SAVE_MODE_NEW, [
  362.                             'builder' => $builder,
  363.                             'language' => $language
  364.                         ]);
  365.                         $this->saveMediaUsages($entity);
  366.                         if ($isParent) {
  367.                             $parentEntity $entity;
  368.                         }
  369.                         if ($this->entity_settings->isRevisable()) {
  370.                             $revision $this->generateRevision($entity);
  371.                             $revision->setPostType('revision');
  372.                             if (is_null($revisionParentEntity)) {
  373.                                 $revision->setLanguageParent(null);
  374.                                 $revisionParentEntity $revision;
  375.                             }
  376.                             else {
  377.                                 $revision->setLanguageParent($revisionParentEntity->getId());
  378.                             }
  379.                             $em->persist($revision);
  380.                             $em->flush();
  381.                             if($approval_required && $revision && $language->getAlias() === $default_lang){
  382.                                 $approval_request $this->createApprovalRequest($revisionApprovalRequest::REQUEST_TYPE_CREATE$this->getUser());
  383.                                 $em->persist($approval_request);
  384.                                 $em->flush();
  385.                                 $this->dispatcher->dispatch(RequestCreatedEvent::NAME, new RequestCreatedEvent($approval_request));
  386.                             }
  387.                         }
  388.                     }
  389.                 }
  390.                 if('preview' !== $buttonAction) {
  391.                     $flash_message $translator->trans('message.entry_saved', [], 'admin');
  392.                     $this->addFlash('success'$flash_message);
  393.                     if ($settings->get('single'false)) {
  394.                         return $this->redirectToRoute($this->routes['edit'], [
  395.                             'facility' => $facility,
  396.                             'id' => ($parentEntity) ? $parentEntity->getId() : $entity->getId(),
  397.                             'disable_redirect_suggestion' => true
  398.                         ]);
  399.                     } else {
  400.                         return $this->redirect($this->base_path);
  401.                     }
  402.                 }
  403.             }
  404.         }
  405.         return $this->render($this->views['multilingual_edit'], [
  406.             'meta' => $this->meta('NEW'),
  407.             '_languages' => $languages,
  408.             'selected_languages' => $selected_languages,
  409.             'active_language' => $active_language,
  410.             'violations' => $violations,
  411.             'builders' => $builders,
  412.             'preview_url' => $preview_url,
  413.             'redirect_url' => null,
  414.             'redirect_message' => null,
  415.             'entity' => null,
  416.             'master_entity' => null,
  417.             'post_type' => null,
  418.             'approval_required' => $approval_required,
  419.             'revisions' => [],
  420.             'revision_history' => [],
  421.             'approval_history' => [],
  422.             'button_sections' => isset($this->button_sections['new']) ? $this->button_sections['new'] : [],
  423.             '_pageBuilderParams' => $_pageBuilderParams,
  424.             '_routes' => $this->routes,
  425.             '_base_route_params' => $this->base_route_params,
  426.             'languages_heading' => $languageHeading
  427.         ]);
  428.     }
  429.     public function editAction(Request $request$id)
  430.     {
  431.         $translator $this->container->get('translator');
  432.         $settings $this->entity_settings;
  433.         if ($this->entity_settings->isMultilingual()) {
  434.             return $this->multiLingualEditAction($request$id);
  435.         }
  436.         $em $this->getDoctrine()->getManager();
  437.         $repo $this->getDoctrine()->getRepository($this->models['item']);
  438.         // new でも見えるようにフィルターを外す
  439.         $filters $em->getFilters();
  440.         if($filters->isEnabled('post_type')){
  441.             $filters->disable('post_type');
  442.             $entity $this->findEntity($id);
  443.             $filters->enable('post_type');
  444.         } else {
  445.             $entity $this->findEntity($id);
  446.         }
  447.         if (!$entity) {
  448.             throw new NotFoundHttpException();
  449.         }
  450.         $master_entity $entity;
  451.         if($this->isGranted('approval_request_edit')){
  452.             $approval_required false;
  453.         } else {
  454.             $approval_required $settings->get('approval_required'false);
  455.         }
  456.         $preview_url null;
  457.         $redirect_url null;
  458.         $redirect_message null;
  459.         $post_type method_exists($entity'getPostType') ? $entity->getPostType() : 'master';
  460.         $suggestion_disabled $request->query->getBoolean('disable_redirect_suggestion'false);
  461.         if($settings->isRevisable()){
  462.             $master_entity $repo->findMasterEntity($entity);
  463.             $revisions $this->getRevisions($entity);
  464.             $revision_history $this->getRevisionHistory($entity);
  465.             if($settings->get('approval_required'false)) {
  466.                 $approval_history $this->getApprovalHistory($master_entity);
  467.             } else {
  468.                 $approval_history = [];
  469.             }
  470.             if(!$suggestion_disabled) {
  471.                 // 新しい下書きがあるか調べる
  472.                 foreach ($revisions as $revision) {
  473.                     if ('draft' === $revision->getPostType() && $revision->getRevisionVersion() > $entity->getRevisionVersion() && $entity->getId() !== $revision->getId()) {
  474.                         $redirect_url $this->get('router')->generate($this->routes['edit'], [
  475.                             'id' => $revision->getId(),
  476.                             'disable_redirect_suggestion' => true
  477.                         ]);
  478.                         $redirect_message '編集中の下書きがあります。表示を切り替えますか?';
  479.                         break;
  480.                     }
  481.                 }
  482.                 // 新しいリビジョンがあるか調べる
  483.                 foreach ($revision_history as $value) {
  484.                     if ($value['version'] > $master_entity->getRevisionVersion() && $entity->getId() !== $revision->getId()) {
  485.                         $redirect_url $this->get('router')->generate($this->routes['edit'], [
  486.                             'id' => $revision->getId(),
  487.                             'disable_redirect_suggestion' => true
  488.                         ]);
  489.                         $redirect_message '新しい項目があります。表示を切り替えますか?';
  490.                         break;
  491.                     }
  492.                 }
  493.             }
  494.             /** @var ButtonSection $topRightButtons */
  495.             $topRightButtons $this->button_sections['edit']['top_right'];
  496.             if($this->entity_settings->get('revisable'false)) {
  497.                 $topRightButtons->addButton('revision_history''<i class="fa fa-history" aria-hidden="true"></i> 変更履歴', [
  498.                     'id' => 'btn-revision-select',
  499.                     'class' => 'btn btn-default',
  500.                     'href' => '#btn-revision-select',
  501.                     'data-toggle' => 'modal',
  502.                     'data-target' => '#revision-history-modal'
  503.                 ], 1000);
  504.             }
  505.             if($this->entity_settings->get('approval_required'false)) {
  506.                 $topRightButtons->addButton('approval_history''<i class="fa fa-check-circle" aria-hidden="true"></i> 承認履歴', [
  507.                     'id' => '',
  508.                     'class' => 'btn btn-default',
  509.                     'href' => 'javascript:void(0)',
  510.                     'data-toggle' => 'modal',
  511.                     'data-target' => '#approval-history-modal'
  512.                 ]);
  513.             }
  514.         } else {
  515.             $revisions = [];
  516.             $revision_history = [];
  517.             $approval_history = [];
  518.         }
  519.         $buttonAction $request->request->get('_button_action''default');
  520.         $builder $this->createPageBuilder($this->form_class$entity'edit');
  521.         $this->pageBuilderOnLoad($builder);
  522.         if ($request->isMethod('post')) {
  523.             $referer $request->headers->get('referer');
  524.             $builder->initMediaUsageTracker();
  525.             $violations $builder->handleRequest($request);
  526.             // エラーがないとき
  527.             if (empty($violations)) {
  528.                 if ($buttonAction === 'preview') {
  529.                     $previews $repo->findChildRevisions($entity, ['preview']);
  530.                     if ($previews) {
  531.                         $preview $previews[0];
  532.                     } else {
  533.                         // プレビューの作成
  534.                         $preview $this->duplicateEntity($entity);
  535.                         $preview->setRevisionParent($entity->getId());
  536.                         $preview->setPostType('preview');
  537.                     }
  538.                     $token $this->generateAccessToken();
  539.                     $blocks2 array_map(function($block){
  540.                         return clone $block;
  541.                     }, $builder->getBlocks());
  542.                     $builder->setBlocks($blocks2);
  543.                     $builder->commit(OnCommitEvent::MODE_PREVIEW);
  544.                     $formData $builder->getData();
  545.                     $formData $this->filterFormData($formData'edit');
  546.                     $preview->bindFormData($formData);
  547.                     $preview->setAccessToken($token);
  548.                     $this->save($em$preview$formDataself::SAVE_MODE_PREVIEW);
  549.                     if($this->entity_settings->isRevisable()) {
  550.                         $previewParams = [
  551.                             'id' => $preview->getId()
  552.                         ];
  553.                         $preview_url $this->generateUrl($this->routes['preview'], array_merge($this->base_route_params$previewParams));
  554.                     } else {
  555.                         $previewParams = [
  556.                             'preview_id' => $preview->getId(),
  557.                             'cms_token' => $token,
  558.                             'cms_mode' => 'tmp_preview'
  559.                         ];
  560.                         $preview_url $this->getPreviewPageUrl($preview->getId(), $previewParams);
  561.                     }
  562.                 } else {
  563.                     $revisionParent null;
  564.                     $revision null;
  565.                     $targetEntity $entity;
  566.                     if ($this->entity_settings->isRevisable()) {
  567.                         $blocks2 array_map(function($block){
  568.                             return clone $block;
  569.                         }, $builder->getBlocks());
  570.                         $builder->setBlocks($blocks2);
  571.                         $builder->commit(OnCommitEvent::MODE_REVISION);
  572.                         $formData $builder->getData();
  573.                         $formData $this->filterFormData($formData'edit');
  574.                         // 一度もリビジョンが作られていない場合
  575.                         if(=== $repo->countRevisions($entity) && 'draft' !== $entity->getPostType()){
  576.                             $firstRevision $this->generateRevision($entity);
  577.                             $firstRevision->setPostType('revision');
  578.                             $em->persist($firstRevision);
  579.                         }
  580.                         // 更新
  581.                         $revision $this->generateRevision($entity);
  582.                         $revision->setPostType(('draft' === $buttonAction) ? 'draft' 'revision');
  583.                         $maxVersion = (int)$repo->getMaxRevisionVersion($entity);
  584.                         $revision->setRevisionVersion($maxVersion 1);
  585.                         $em->persist($revision);
  586.                         $targetEntity $revision;
  587.                         // 不要になった下書きを削除
  588.                         $drafts = ($master_entity) ? $this->getRelatedDrafts($master_entity) : [];
  589.                         foreach ($drafts as $draft) {
  590.                             if($targetEntity->getId() === $draft->getId()){
  591.                                 continue;
  592.                             }
  593.                             $em->remove($draft);
  594.                         }
  595.                     } else {
  596.                         $builder->commit();
  597.                         $formData $builder->getData();
  598.                         $formData $this->filterFormData($formData'edit');
  599.                     }
  600.                     $targetEntity->bindFormData($formData);
  601.                     $flash_message $translator->trans('message.entry_saved', [], 'admin');
  602.                     $this->save($em$targetEntity$formDataself::SAVE_MODE_EDIT);
  603.                     if ($this->entity_settings->isRevisable() && $revision) {
  604.                         $approval_request null;
  605.                         if('draft' === $buttonAction){
  606.                             // 下書きの再編集
  607.                             if('master:draft' === $master_entity->getPostType()){
  608.                                 $this->applyRevision($master_entity$revision);
  609.                             }
  610.                         } else {
  611.                             if($approval_required){
  612.                                 if('master:draft' === $master_entity->getPostType()){
  613.                                     $approval_request $this->createApprovalRequest($revisionApprovalRequest::REQUEST_TYPE_CREATE$this->getUser());
  614.                                 } else {
  615.                                     $approval_request $this->createApprovalRequest($revisionApprovalRequest::REQUEST_TYPE_UPDATE$this->getUser());
  616.                                 }
  617.                                 $em->persist($approval_request);
  618.                                 // 下書き、または承認前なら即時反映
  619.                                 if(in_array($master_entity->getPostType(), ['master:draft''master:unapproved''master:rejected'])){
  620.                                     $this->applyRevision($master_entity$revision);
  621.                                     $master_entity->setPostType('master:unapproved');
  622.                                 }
  623.                             } else {
  624.                                 if ('master:draft' === $master_entity->getPostType()) {
  625.                                     $master_entity->setPostType('master');
  626.                                 }
  627.                                 $this->applyRevision($master_entity$revision);
  628.                                 $this->cancelRelatedApprovalRequests($master_entity);
  629.                             }
  630.                         }
  631.                         if($approval_request){
  632.                             $this->dispatcher->dispatch(RequestCreatedEvent::NAME, new RequestCreatedEvent($approval_request));
  633.                         }
  634.                         $em->flush();
  635.                         $this->saveMediaUsages($revision);
  636.                     }
  637.                     $this->saveMediaUsages($master_entity);
  638.                     $this->addFlash('success'$flash_message);
  639.                     if($settings->get('single'false)){
  640.                         return $this->redirectToRoute($this->routes['edit'], [
  641.                             'id' => $targetEntity->getId(),
  642.                             'disable_redirect_suggestion' => true
  643.                         ]);
  644.                     } else {
  645.                         return $this->redirect($this->base_path);
  646.                     }
  647.                 }
  648.             }
  649.         }
  650.         if('' !== (string)$preview_url){
  651.             $redirect_url null;
  652.             $redirect_message null;
  653.         }
  654.         return $this->render($this->views['edit'], [
  655.             'meta' => $this->meta('EDIT'),
  656.             'builder' => $builder,
  657.             'preview_url' => $preview_url,
  658.             'redirect_url' => $redirect_url,
  659.             'redirect_message' => $redirect_message,
  660.             'entity' => $entity,
  661.             'master_entity' => $master_entity,
  662.             'post_type' => $post_type,
  663.             'approval_required' => $approval_required,
  664.             'revisions' => $revisions,
  665.             'revision_history' => $revision_history,
  666.             'approval_history' => $approval_history,
  667.             'drafts' => [],
  668.             'button_sections' => isset($this->button_sections['edit']) ? $this->button_sections['edit'] : [],
  669.             '_pageBuilderParams' => $builder->getSharedParams(),
  670.             '_routes' => $this->routes,
  671.             '_base_route_params' => $this->base_route_params,
  672.         ]);
  673.     }
  674.     public function multiLingualEditAction(Request $request$id)
  675.     {
  676.         $facility 'master';
  677.         $this->get('app.helper.script_loader')
  678.             ->register('language_edit'CMS__ADMIN_PATH 'js/pages/language-edit.js');
  679.         $translator $this->container->get('translator');
  680.         $settings $this->entity_settings;
  681.         $languages $this->getMasterLanguages();
  682.         $em $this->getDoctrine()->getManager();
  683.         $repo $this->getDoctrine()->getRepository($this->models['item']);
  684.         $default_lang $this->container->getParameter('language.default''jp');
  685.         $languageHeading $this->getLanguagesHeading($languages);
  686.         $revision_parent $request->query->get('revision_parent'null);
  687.         if (empty($revision_parent)) {
  688.             $revision_parent $id;
  689.         }
  690.         $revision_lang $request->query->get('revision_lang'null);
  691.         $active_language $request->request->get('_active-language'null);
  692.         if (!empty($revision_lang)) {
  693.             $active_language $revision_lang;
  694.         }
  695.         // new でも見えるようにフィルターを外す
  696.         /** @var FilterCollection $filters */
  697.         $filters $em->getFilters();
  698.         if($filters->isEnabled('post_type')){
  699.             $postTypeFilter $filters->getFilter('post_type');
  700.             $postTypeFilter->saveState();
  701.             $postTypeFilter->deactivate();
  702.         } else {
  703.             $postTypeFilter null;
  704.         }
  705.         $entities $repo->getEntitiesForLanguage($id$revision_parent$revision_lang);
  706.         $trunk $repo->findTrunkLanguageEntry($id$default_lang);
  707.         if($postTypeFilter){
  708.             $postTypeFilter->restoreState();
  709.         }
  710.         $defaultSelected = [];
  711.         foreach ($entities as $k => $entity) {
  712.             if ($entity->isLanguageActive()) {
  713.                 $defaultSelected[] = $k;
  714.             }
  715.         }
  716.         $selected_languages $request->request->get('select_lang'$defaultSelected);
  717.         if (!is_null($active_language) && !in_array($active_language$selected_languages)) {
  718.             $selected_languages[] = $active_language;
  719.         }
  720.         $master_entity $trunk;
  721.         if($this->isGranted('approval_request_edit')){
  722.             $approval_required false;
  723.         } else {
  724.             $approval_required $settings->get('approval_required'false);
  725.         }
  726.         $violations = [];
  727.         // 言語ごとのbuilderを設定
  728.         $builders $this->createPageBuilderLanguages($languages$entities'edit');
  729.         $preview_url null;
  730.         $redirect_url null;
  731.         $redirect_message null;
  732.         $post_type null;
  733.         $suggestion_disabled $request->query->getBoolean('disable_redirect_suggestion'false);
  734.         $revisions = [];
  735.         $first_entity = isset($entities[$active_language]) ? $entities[$active_language] : reset($entities);
  736.         if($settings->isRevisable()) {
  737.             $master_entity = ($trunk) ? $repo->findMasterEntity($trunk) : null;
  738.             $revision_history $this->getRevisionHistory($trunk);
  739.             if($settings->get('approval_required'false)) {
  740.                 $approval_history $this->getApprovalHistory($trunk);
  741.             } else {
  742.                 $approval_history = [];
  743.             }
  744.             if(!$suggestion_disabled) {
  745.                 // 新しい下書きがあるか調べる
  746.                 foreach ($revisions as $revision) {
  747.                     if ('draft' === $revision->getPostType() && $revision->getRevisionVersion() > $entity->getRevisionVersion() && $entity->getId() !== $revision->getId()) {
  748.                         $redirect_url $this->get('router')->generate($this->routes['edit'], [
  749.                             'facility' => $facility'id' => $revision->getId(),
  750.                             'disable_redirect_suggestion' => 1
  751.                         ]);
  752.                         $redirect_message '編集中の下書きがあります。表示を切り替えますか?';
  753.                         break;
  754.                     }
  755.                 }
  756.                 // 新しいリビジョンがあるか調べる
  757.                 foreach ($revision_history as $value) {
  758.                     if ($value['version'] > $master_entity->getRevisionVersion() && $entity->getId() !== $value['id']) {
  759.                         $redirect_url $value['edit_url'];
  760.                         $redirect_message '新しい項目があります。表示を切り替えますか?';
  761.                         break;
  762.                     }
  763.                 }
  764.             }
  765.             /** @var ButtonSection $topRightButtons */
  766.             $topRightButtons $this->button_sections['edit']['top_right'];
  767.             if($this->entity_settings->get('revisable'false)) {
  768.                 $topRightButtons->addButton('revision_history''<i class="fa fa-history" aria-hidden="true"></i> 変更履歴', [
  769.                     'id' => 'btn-revision-history',
  770.                     'class' => 'btn btn-default',
  771.                     'href' => '#revision-history-modal',
  772.                     'data-toggle' => 'modal',
  773.                     'data-target' => '#revision-history-modal'
  774.                 ], 1000);
  775.             }
  776.             if($this->entity_settings->get('approval_required'false)) {
  777.                 $topRightButtons->addButton('approval_history''<i class="fa fa-check-circle" aria-hidden="true"></i> 承認履歴', [
  778.                     'id' => 'btn-approval-history',
  779.                     'class' => 'btn btn-default',
  780.                     'href' => '#approval-history-modal',
  781.                     'data-toggle' => 'modal',
  782.                     'data-target' => '#approval-history-modal'
  783.                 ]);
  784.             }
  785.         } else {
  786.             $revisions = [];
  787.             $revision_history = [];
  788.             $approval_history = [];
  789.         }
  790.         $buttonAction $request->request->get('_button_action''default');
  791.         $_pageBuilderParams = [];
  792.         foreach ($builders as $builder) {
  793.             $_pageBuilderParams += $builder->getSharedParams();
  794.         }
  795.         if ($request->isMethod('post')) {
  796.             $violations $this->validateLanguages($request$builders$selected_languages$buttonAction);
  797.             if (empty($violations)) {
  798.                 // 不足言語分のEntityを先に作成
  799.                 foreach ($languages as $language) {
  800.                     $formData = [];
  801.                     $alias $language->getAlias();
  802.                     if (!isset($entities[$alias])) {
  803.                         $entity = new $this->models['item']();
  804.                         $max = (method_exists($entity'getSortNum')) ? $repo->getMaxSortNumForLanguage($language$language->isParent()) : 0;
  805.                         $defaults = [
  806.                             'max' => $max,
  807.                             'buttonAction' => $buttonAction,
  808.                             'language' => $language,
  809.                             'parentEntity' => $entities[$default_lang],
  810.                             'alias' => $alias,
  811.                             'selected_languages' => []
  812.                         ];
  813.                         $this->setLanguageEntityDefault($entity$defaults);
  814.                         $entity->bindFormData($formData);
  815.                         $em->persist($entity);
  816.                         $em->flush();
  817.                         $entities[$alias] = $entity;
  818.                     }
  819.                 }
  820.                 $parentEntity null;
  821.                 $parentMasterEntity null;
  822.                 $parentFirstRevisionEntity null;
  823.                 /** @var Language $language */
  824.                 foreach ($languages as $language) {
  825.                     $alias $language->getAlias();
  826.                     $isParent $language->isParent();
  827.                     $prefix $language->getTranslateKey() . '_';
  828.                     $builder $builders[$alias];
  829.                     $builder->initMediaUsageTracker();
  830.                     $entity $entities[$alias];
  831.                     if ($buttonAction === 'preview') {
  832.                         if ($alias !== $active_language) {
  833.                             continue;
  834.                         }
  835.                         $previews $repo->findChildRevisions($entity, ['preview']);
  836.                         if($previews){
  837.                             $preview $previews[0];
  838.                         } else {
  839.                             // プレビューの作成
  840.                             $preview $this->duplicateEntity($entity);
  841.                             $preview->setPostType('preview');
  842.                         }
  843.                         $preview->setRevisionParent($entity->getId());
  844.                         $token $this->generateAccessToken();
  845.                         $defaults = [
  846.                             'language' => $language,
  847.                             'parentEntity' => $parentEntity,
  848.                             'alias' => $alias,
  849.                         ];
  850.                         $this->setLanguageEntityDefault($preview$defaults);
  851.                         $blocks2 array_map(function($block){
  852.                             return clone $block;
  853.                         }, $builder->getBlocks());
  854.                         $builder->setBlocks($blocks2);
  855.                         $builder->commit(OnCommitEvent::MODE_PREVIEW);
  856.                         $formData $builder->getData();
  857.                         $formData $this->filterFormDataLanguage($formData'edit'$prefix);
  858.                         $formData $this->filterFormData($formData'edit');
  859.                         $preview->bindFormData($formData);
  860.                         $preview->setAccessToken($token);
  861.                         $this->save($em$preview$formDataself::SAVE_MODE_PREVIEW);
  862.                         if($this->entity_settings->isRevisable()) {
  863.                             $previewParams = [
  864.                                 'id' => $preview->getId()
  865.                             ];
  866.                             $preview_url $this->generateUrl($this->routes['preview'], array_merge($this->base_route_params$previewParams));
  867.                         } else {
  868.                             $previewParams = [
  869.                                 'preview_id' => $preview->getId(),
  870.                                 'cms_token' => $token,
  871.                                 'cms_mode' => 'tmp_preview',
  872.                                 '_locale' => $preview->getLanguageAlias()
  873.                             ];
  874.                             $preview_url $this->getPreviewPageUrl($facility$preview->getId(), $previewParams);
  875.                         }
  876.                     } else {
  877.                         $revisionParent null;
  878.                         $revision null;
  879.                         $targetEntity $entity;
  880.                         if ($this->entity_settings->isRevisable()) {
  881.                             $blocks2 array_map(function($block){
  882.                                 return clone $block;
  883.                             }, $builder->getBlocks());
  884.                             $builder->setBlocks($blocks2);
  885.                             $builder->commit(OnCommitEvent::MODE_REVISION);
  886.                             $formData $builder->getData();
  887.                             $formData $this->filterFormDataLanguage($formData'edit'$prefix);
  888.                             $languageMaster $repo->findMasterEntity($entity);
  889.                             $parentId $entity->getRevisionParent();
  890.                             $revisionParent = ($parentId) ? $repo->findRevision($parentId) : null;
  891.                             if ('draft' === $entity->getPostType()) {
  892.                                 $targetEntity $entity;
  893.                                 if($revisionParent){
  894.                                     // 既存下書き
  895.                                     $revision $entity;
  896.                                     $revision->setPostType(('draft' === $buttonAction) ? 'draft' 'revision');
  897.                                 } else {
  898.                                     // 新規下書き
  899.                                     $targetEntity->setPostType(('draft' === $buttonAction) ? 'draft' 'master');
  900.                                 }
  901.                             } else {
  902.                                 // 一度もリビジョンが作られていない場合
  903.                                 if(=== $repo->countRevisions($entity) && 'draft' !== $entity->getPostType()){
  904.                                     $firstRevision $this->generateRevision($entity);
  905.                                     $firstRevision->setPostType('revision');
  906.                                     if (is_null($parentFirstRevisionEntity)) {
  907.                                         $firstRevision->setLanguageParent(null);
  908.                                         $parentFirstRevisionEntity $firstRevision;
  909.                                     }
  910.                                     else {
  911.                                         $firstRevision->setLanguageParent($parentFirstRevisionEntity->getId());
  912.                                     }
  913.                                     $em->persist($firstRevision);
  914.                                 }
  915.                                 // 更新
  916.                                 $revision $this->generateRevision($entity);
  917.                                 $revision->setPostType(('draft' === $buttonAction) ? 'draft' 'revision');
  918.                                 $maxVersion = (int)$repo->getMaxRevisionVersion($entity);
  919.                                 $revision->setRevisionVersion($maxVersion 1);
  920.                                 $em->persist($revision);
  921.                                 $targetEntity $revision;
  922.                             }
  923.                             // 不要になった下書きを削除
  924.                             $drafts = ($languageMaster) ? $this->getRelatedDrafts($languageMaster) : [];
  925.                             foreach ($drafts as $draft) {
  926.                                 if($targetEntity->getId() === $draft->getId()){
  927.                                     continue;
  928.                                 }
  929.                                 $em->remove($draft);
  930.                             }
  931.                         } else {
  932.                             $languageMaster $entity;
  933.                             $builder->commit();
  934.                             $formData $builder->getData();
  935.                             $formData $this->filterFormDataLanguage($formData'edit'$prefix);
  936.                         }
  937.                         if ($parentEntity) {
  938.                             $this->setEntityParentLanguage($targetEntity$parentEntity$this->form_class);
  939.                         }
  940.                         $targetEntity->bindFormData($formData);
  941.                         $defaults = [
  942.                             'language' => $language,
  943.                             'alias' => $alias,
  944.                             'selected_languages' => $selected_languages,
  945.                             'parentEntity' => $parentEntity,
  946.                         ];
  947.                         $this->setLanguageEntityDefault($targetEntity$defaults);
  948.                         $this->save($em$targetEntity$formDataself::SAVE_MODE_EDIT, [
  949.                             'builder' => $builder,
  950.                             'language' => $language
  951.                         ]);
  952.                         if ($isParent) {
  953.                             $parentEntity $targetEntity;
  954.                         }
  955.                         if ($this->entity_settings->isRevisable() && $revision) {
  956.                             $approval_request null;
  957.                             if('draft' === $buttonAction){
  958.                                 // 下書きの再編集
  959.                                 if('master:draft' === $languageMaster->getPostType()){
  960.                                     $this->applyRevision($languageMaster$revision);
  961.                                 }
  962.                             } else {
  963.                                 if($approval_required){
  964.                                     if($language->getAlias() !== $default_lang){
  965.                                         $approval_request null;
  966.                                     } elseif('master:draft' === $master_entity->getPostType()){
  967.                                         $approval_request $this->createApprovalRequest($revisionApprovalRequest::REQUEST_TYPE_CREATE$this->getUser());
  968.                                     } else {
  969.                                         $approval_request $this->createApprovalRequest($revisionApprovalRequest::REQUEST_TYPE_UPDATE$this->getUser());
  970.                                     }
  971.                                     if($approval_request) {
  972.                                         $em->persist($approval_request);
  973.                                     }
  974.                                     // 下書き、または承認前なら即時反映
  975.                                     if(in_array($languageMaster->getPostType(), ['master:draft''master:unapproved''master:rejected'])){
  976.                                         $this->applyRevision($languageMaster$revision);
  977.                                         $master_entity->setPostType('master:unapproved');
  978.                                     }
  979.                                 } else {
  980.                                     if (in_array($languageMaster->getPostType(), ['master:draft''master:unapproved''master:rejected'])) {
  981.                                         $languageMaster->setPostType('master');
  982.                                     }
  983.                                     $this->applyRevision($languageMaster$revision);
  984.                                     $this->cancelRelatedApprovalRequests($languageMaster);
  985.                                 }
  986.                             }
  987.                             $em->flush();
  988.                             if($approval_request){
  989.                                 $this->dispatcher->dispatch(RequestCreatedEvent::NAME, new RequestCreatedEvent($approval_request));
  990.                             }
  991.                             $this->saveMediaUsages($revision);
  992.                         }
  993.                     }
  994.                 }
  995.                 if ($buttonAction !== 'preview') {
  996.                     $this->saveMediaUsages($master_entity);
  997.                     $flash_message $translator->trans('message.entry_saved', [], 'admin');
  998.                     $this->addFlash('success'$flash_message);
  999.                     if ($settings->get('single'false)) {
  1000.                         return $this->redirectToRoute($this->routes['edit'], [
  1001.                             'facility' => $facility,
  1002.                             'id' => $trunk->getId(),
  1003.                             'disable_redirect_suggestion' => true
  1004.                         ]);
  1005.                     } else {
  1006.                         return $this->redirect($this->base_path);
  1007.                     }
  1008.                 }
  1009.             }
  1010.         }
  1011.         if('' !== (string)$preview_url){
  1012.             $redirect_url null;
  1013.             $redirect_message null;
  1014.         }
  1015.         return $this->render($this->views['multilingual_edit'], [
  1016.             'meta' => $this->meta('EDIT'),
  1017.             'builders' => $builders,
  1018.             'preview_url' => $preview_url,
  1019.             'redirect_url' => $redirect_url,
  1020.             'redirect_message' => $redirect_message,
  1021.             '_languages' => $languages,
  1022.             'selected_languages' => $selected_languages,
  1023.             'active_language' => $active_language,
  1024.             'violations' => $violations,
  1025.             'entity' => $first_entity,
  1026.             'master_entity' => $master_entity,
  1027.             'post_type' => $post_type,
  1028.             'approval_required' => $approval_required,
  1029.             'revisions' => $revisions,
  1030.             'revision_history' => $revision_history,
  1031.             'approval_history' => $approval_history,
  1032.             'button_sections' => isset($this->button_sections['edit']) ? $this->button_sections['edit'] : [],
  1033.             '_pageBuilderParams' => $_pageBuilderParams,
  1034.             '_routes' => $this->routes,
  1035.             '_base_route_params' => $this->base_route_params,
  1036.             'revision_parent' => $revision_parent,
  1037.             'languages_heading' => $languageHeading
  1038.         ]);
  1039.     }
  1040.     /**
  1041.      * @param Request $request
  1042.      * @param $id
  1043.      * @return Response
  1044.      */
  1045.     public function detailAction(Request $request$id)
  1046.     {
  1047.         $em $this->getDoctrine()->getManager();
  1048.         /** @var FilterCollection $filters */
  1049.         $filters $em->getFilters();
  1050.         if($filters->isEnabled('post_type')){
  1051.             $filter $filters->getFilter('post_type');
  1052.             $filterState $filter->isActive();
  1053.             $filter->deactivate();
  1054.         } else {
  1055.             $filter null;
  1056.             $filterState false;
  1057.         }
  1058.         $item $this->findOneEntity($this->models['item'], ['id' => $id]);
  1059.         if(!$item){
  1060.             throw $this->createNotFoundException();
  1061.         }
  1062.         if($filterState){
  1063.             $filter->activate();
  1064.         }
  1065.         $builder $this->createPageBuilder($this->form_class$item);
  1066.         $builder->setTheme('browse');
  1067.         return $this->render($this->views['detail'], [
  1068.             'item' => $item,
  1069.             'builder' => $builder,
  1070.             'page_title' => $this->title
  1071.         ]);
  1072.     }
  1073.     public function deleteAction(Request $request)
  1074.     {
  1075.         $translator $this->get('translator');
  1076.         $id $request->get('id', -1);
  1077.         $em $this->getDoctrine()->getManager();
  1078.         $repo $this->getDoctrine()->getRepository($this->models['item']);
  1079.         $filters $em->getFilters();
  1080.         if($filters->isEnabled('post_type')){
  1081.             $filters->disable('post_type');
  1082.         }
  1083.         $item $repo->find($id);
  1084.         if($filters->isEnabled('post_type')){
  1085.             $filters->enable('post_type');
  1086.         }
  1087.         if(!$item) throw $this->createNotFoundException();
  1088.         if(method_exists($item'getPostType')){
  1089.             $post_type $item->getPostType();
  1090.         } else {
  1091.             $post_type 'master';
  1092.         }
  1093.         if($this->isGranted('approval_request_edit')){
  1094.             $approval_required false;
  1095.         } else {
  1096.             $approval_required $this->entity_settings->get('approval_required'false);
  1097.         }
  1098.         if('master' === $post_type && $approval_required) {
  1099.             $approval_request $this->createApprovalRequest($itemApprovalRequest::REQUEST_TYPE_DELETE$this->getUser());
  1100.             $em->persist($approval_request);
  1101.             $em->flush();
  1102.             // フラッシュメッセージ
  1103.             $this->addFlash('success'$translator->trans('approval.message.entry_delete_requested', [], 'admin'));
  1104.             $this->dispatcher->dispatch(RequestCreatedEvent::NAME, new RequestCreatedEvent($approval_request));
  1105.         } else {
  1106.             $em->remove($item);
  1107.             $em->flush();
  1108.             // フラッシュメッセージ
  1109.             $this->addFlash('success'$translator->trans('message.entry_deleted', [], 'admin'));
  1110.         }
  1111.         return $this->redirect($this->base_path);
  1112.     }
  1113.     public function sortAction(Request $request)
  1114.     {
  1115.         $meta $this->meta('INDEX');
  1116.         if ($request->isMethod('post')) {
  1117.             $order $request->get('order''');
  1118.             $idList preg_split('/,/'$order, -1, \PREG_SPLIT_NO_EMPTY);
  1119.             $sortOrder array_flip($idList);
  1120.             $doctrine $this->getDoctrine();
  1121.             $em $doctrine->getManager();
  1122.             $repository $em->getRepository($this->models['item']);
  1123.             $entities $repository->createQueryBuilder('i')
  1124.                 ->select('i')
  1125.                 ->where('i.id IN(:ids)')
  1126.                 ->setParameter('ids'array_values($idList))
  1127.                 ->getQuery()
  1128.                 ->getResult();
  1129.             foreach ($entities as $entity) {
  1130.                 $entity->setSortNum($sortOrder[$entity->getId()] + 1);
  1131.                 $em->persist($entity);
  1132.             }
  1133.             $em->flush();
  1134.             // フラッシュメッセージ
  1135.             $this->addFlash('success'$this->title MSG_SORT_END);
  1136.             return $this->redirectToRoute($this->entity_settings->get('base_route') . '_sort');
  1137.         }
  1138.         $data_table_options $this->getSortDataTableOptions();
  1139.         return $this->render($this->views['sort'], [
  1140.             'meta' => $meta,
  1141.             'data_table_options' => $data_table_options,
  1142.             'button_sections' => isset($this->button_sections['sort']) ? $this->button_sections['sort'] : [],
  1143.         ]);
  1144.     }
  1145.     // ID からエンティティを取得
  1146.     protected function findEntity($id)
  1147.     {
  1148.         $repo $this->getDoctrine()->getRepository($this->models['item']);
  1149.         $entity $repo->find($id);
  1150.         return $entity;
  1151.     }
  1152.     public function importAction(Request $request)
  1153.     {
  1154.         $meta $this->meta('IMPORT');
  1155.         $builder $this->createPageBuilder(AdminImportForm::class, null);
  1156.         if ($request->isMethod('post')) {
  1157.             // ファイル取得
  1158.             $file $request->files->get("__block_file")["file"];
  1159.             $import $this->get("app.helper.import_helper");
  1160.             $formatData $import->getFormatData($request->request->all(), $file);
  1161.             if (!empty($formatData) && method_exists($this"importExecuting")) {
  1162.                 $this->importExecuting($formatData);
  1163.                 return $this->redirectToRoute($meta["redirect"]);
  1164.             }
  1165.         }
  1166.         return $this->render(rtrim($this->template_directory) . '/' 'import.html.php', [
  1167.             'meta' => $meta,
  1168.             'builder' => $builder
  1169.         ]);
  1170.     }
  1171.     protected function meta($mode$id null)
  1172.     {
  1173.         $meta = array();
  1174.         $meta["base"]["title"] = $this->title;
  1175.         $meta["base"]["path"] = $this->base_path;
  1176.         $meta["base"]['route'] = $this->entity_settings->getBaseRoute();
  1177.         $meta["redirect"] = $this->entity_settings->getBaseRoute();
  1178.         return $this->baseMeta($mode$meta$id);
  1179.     }
  1180.     protected function baseMeta($mode$meta = [], $id null)
  1181.     {
  1182.         switch ($mode) {
  1183.             case "INDEX":
  1184.                 $meta["page"]["title"] = $meta["base"]["title"] . " | 一覧";
  1185.                 $meta["page"]["path"] = $meta["base"]["path"];
  1186.                 $meta["breadcrumbs"]["current"]["title"] = $meta["base"]["title"];
  1187.                 $meta["breadcrumbs"]["parent"]["title"] = "TOP";
  1188.                 $meta["breadcrumbs"]["parent"]["path"] = "/admin/";
  1189.                 break;
  1190.             case "NEW":
  1191.                 $meta["page"]["title"] = $meta["base"]["title"] . " | 新規作成";
  1192.                 $meta["page"]["path"] = $meta["base"]["path"] . "new/";
  1193.                 $meta["breadcrumbs"]["current"]["title"] = "新規作成";
  1194.                 $meta["breadcrumbs"]["parent"]["title"] = $meta["base"]["title"];
  1195.                 $meta["breadcrumbs"]["parent"]["path"] = $meta["base"]["path"];
  1196.                 break;
  1197.             case "DETAIL":
  1198.                 $meta["page"]["title"] = $meta["base"]["title"] . " | 詳細";
  1199.                 $meta["page"]["path"] = $meta["base"]["path"] . $id '/';
  1200.                 $meta["breadcrumbs"]["current"]["title"] = "詳細";
  1201.                 $meta["breadcrumbs"]["parent"]["title"] = $meta["base"]["title"];
  1202.                 $meta["breadcrumbs"]["parent"]["path"] = $meta["base"]["path"];
  1203.                 break;
  1204.             case "EDIT":
  1205.                 $meta["page"]["title"] = $meta["base"]["title"] . " | 編集";
  1206.                 $meta["page"]["path"] = $meta["base"]["path"] . $id '/edit/';
  1207.                 $meta["breadcrumbs"]["current"]["title"] = "編集";
  1208.                 $meta["breadcrumbs"]["parent"]["title"] = $meta["base"]["title"];
  1209.                 $meta["breadcrumbs"]["parent"]["path"] = $meta["base"]["path"];
  1210.                 break;
  1211.             case "IMPORT":
  1212.                 $meta["page"]["title"] = $meta["base"]["title"] . " | インポート";
  1213.                 $meta["page"]["path"] = $meta["base"]["path"] . "import/";
  1214.                 $meta["breadcrumbs"]["current"]["title"] = "インポート";
  1215.                 $meta["breadcrumbs"]["parent"]["title"] = $meta["base"]["title"];
  1216.                 $meta["breadcrumbs"]["parent"]["path"] = $meta["base"]["path"];
  1217.                 break;
  1218.             default:
  1219.                 $meta["page"]["title"] = "[Unknown]";
  1220.                 $meta["page"]["path"] = "/unknown";
  1221.                 $meta["breadcrumbs"]["current"]["title"] = "[Unknown]";
  1222.                 $meta["breadcrumbs"]["parent"]["title"] = "[Unknown]";
  1223.                 $meta["breadcrumbs"]["parent"]["path"] = "/unknown";
  1224.         }
  1225.         return $meta;
  1226.     }
  1227.     protected function getListDataTableOptions()
  1228.     {
  1229.         return parent::getListDataTableOptions();
  1230.     }
  1231.     /**
  1232.      * @param int id
  1233.      * @param array $params
  1234.      * @return string|null
  1235.      */
  1236.     protected function getPreviewPageUrl($id$params = [])
  1237.     {
  1238.         if ($this->entity_settings->get('actions.preview')) {
  1239.             return $this->generateUrl($this->routes['preview'], $params);
  1240.         } else {
  1241.             return null;
  1242.         }
  1243.     }
  1244.     /**
  1245.      * @param Request $request
  1246.      * @param $id
  1247.      * @return RedirectResponse
  1248.      */
  1249.     public function duplicateAction(Request $request$id)
  1250.     {
  1251.         if($this->isGranted('approval_request_edit')){
  1252.             $approval_required false;
  1253.         } else {
  1254.             $approval_required $this->entity_settings->get('approval_required'false);
  1255.         }
  1256.         $repo $this->getDoctrine()->getRepository($this->models['item']);
  1257.         $em $this->getDoctrine()->getManager();
  1258.         $filters $em->getFilters();
  1259.         $filterState $filters->isEnabled('post_type');
  1260.         if($filterState){
  1261.             $filters->disable('post_type');
  1262.         }
  1263.         $entity $repo->find($id);
  1264.         if(!$entity){
  1265.             throw $this->createNotFoundException();
  1266.         }
  1267.         if($filterState){
  1268.             $filters->enable('post_type');
  1269.         }
  1270.         $clone $this->duplicateEntityWithForm($entity$this->form_class);
  1271.         if(method_exists($clone'getTitle') && method_exists($clone'setTitle')){
  1272.             $clone->setTitle('(複製)' $clone->getTitle());
  1273.         }
  1274.         if(method_exists($clone'setStatus')){
  1275.             $clone->setStatus(0);
  1276.         }
  1277.         if($approval_required){
  1278.             $post_type = (method_exists($clone'getPostType')) ? $clone->getPostType() : 'master';
  1279.             if('master' === $post_type){
  1280.                 $clone->setPostType('master:unapproved');
  1281.             }
  1282.         }
  1283.         if(method_exists($clone'setLatestApprovalRequest')){
  1284.             $clone->setLatestApprovalRequest(null);
  1285.         }
  1286.         $this->save($em$clone, [], self::SAVE_MODE_DUPLICATE);
  1287.         $this->saveMediaUsages($clone);
  1288.         return $this->redirectToRoute($this->entity_settings->get('base_route'));
  1289.     }
  1290.     public function childIndexAction(Request $request$parent)
  1291.     {
  1292.         /** @var ButtonSection $section */
  1293.         $section = isset($this->button_sections['index']['top_left']) ? $this->button_sections['index']['top_left'] : new ButtonSection();
  1294.         $section->addButton('back''<i class="fa fa-arrow-circle-left"></i> 一覧に戻る', [
  1295.             'href' => '../../',
  1296.             'class' => 'btn btn-default'
  1297.         ], 10);
  1298.         return $this->indexAction($request);
  1299.     }
  1300.     public function childEditAction(Request $request$parent$id)
  1301.     {
  1302.         return $this->editAction($request$id);
  1303.     }
  1304.     public function childJsonAction(Request $request$parent)
  1305.     {
  1306.         return $this->jsonAction($request);
  1307.     }
  1308.     public function childSortAction(Request $request$parent)
  1309.     {
  1310.         return $this->sortAction($request);
  1311.     }
  1312.     public function childDuplicateAction(Request $request$parent$id)
  1313.     {
  1314.         return $this->duplicateAction($request$id);
  1315.     }
  1316.     public function childDeleteAction(Request $request$parent)
  1317.     {
  1318.         return $this->deleteAction($request);
  1319.     }
  1320.     /**
  1321.      * デフォルトの並び順
  1322.      *
  1323.      * @return array
  1324.      */
  1325.     protected function getDefaultOrderBy()
  1326.     {
  1327.         return ['sort_num' => 'ASC''id' => 'DESC'];
  1328.     }
  1329.     /**
  1330.      * @param $entity_class
  1331.      * @param $data
  1332.      * @param string $value_name
  1333.      * @return mixed
  1334.      */
  1335.     protected function getCategoryIdForImport($entity_class$data$value_name "title")
  1336.     {
  1337.         $repository $this->getDoctrine()->getRepository($entity_class);
  1338.         $entries $repository->findBy(["{$value_name}=> $data[$value_name]]);
  1339.         if (!empty($entries)) {
  1340.             return $entries[0];
  1341.         } else {
  1342.             // 新規登録
  1343.             $em $this->getDoctrine()->getManager();
  1344.             $entity = new $entity_class();
  1345.             $entity->bindFormData($data);
  1346.             $em->persist($entity);
  1347.             $em->flush();
  1348.             return $entity;
  1349.         }
  1350.     }
  1351. }