Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

472 lines
18KB

  1. <?php
  2. namespace Lc\SovBundle\Controller;
  3. use Doctrine\ORM\EntityManagerInterface;
  4. use Doctrine\ORM\QueryBuilder;
  5. use EasyCorp\Bundle\EasyAdminBundle\Collection\FieldCollection;
  6. use EasyCorp\Bundle\EasyAdminBundle\Collection\FilterCollection;
  7. use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
  8. use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
  9. use EasyCorp\Bundle\EasyAdminBundle\Config\Assets;
  10. use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
  11. use EasyCorp\Bundle\EasyAdminBundle\Config\KeyValueStore;
  12. use EasyCorp\Bundle\EasyAdminBundle\Config\Option\EA;
  13. use EasyCorp\Bundle\EasyAdminBundle\Context\AdminContext;
  14. use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController as EaAbstractCrudController;
  15. use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
  16. use EasyCorp\Bundle\EasyAdminBundle\Dto\SearchDto;
  17. use EasyCorp\Bundle\EasyAdminBundle\Event\AfterCrudActionEvent;
  18. use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityUpdatedEvent;
  19. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeCrudActionEvent;
  20. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityDeletedEvent;
  21. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
  22. use EasyCorp\Bundle\EasyAdminBundle\Exception\ForbiddenActionException;
  23. use EasyCorp\Bundle\EasyAdminBundle\Exception\InsufficientEntityPermissionException;
  24. use EasyCorp\Bundle\EasyAdminBundle\Factory\EntityFactory;
  25. use EasyCorp\Bundle\EasyAdminBundle\Factory\FilterFactory;
  26. use EasyCorp\Bundle\EasyAdminBundle\Factory\PaginatorFactory;
  27. use EasyCorp\Bundle\EasyAdminBundle\Field\FormField;
  28. use EasyCorp\Bundle\EasyAdminBundle\Field\TextareaField;
  29. use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
  30. use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
  31. use EasyCorp\Bundle\EasyAdminBundle\Security\Permission;
  32. use Lc\SovBundle\Doctrine\EntityManager;
  33. use Lc\SovBundle\Doctrine\Extension\DevAliasInterface;
  34. use Lc\SovBundle\Doctrine\Extension\SeoInterface;
  35. use Lc\SovBundle\Doctrine\Extension\SortableInterface;
  36. use Lc\SovBundle\Doctrine\Extension\TranslatableInterface;
  37. use Lc\SovBundle\Doctrine\Extension\TreeInterface;
  38. use Lc\SovBundle\Field\CollectionField;
  39. use Lc\SovBundle\Field\GalleryManagerField;
  40. use Lc\SovBundle\Form\Type\Crud\PositionType;
  41. use Lc\SovBundle\Translation\TranslatorAdmin;
  42. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  43. use Symfony\Component\Form\Extension\Core\Type\CollectionType;
  44. use Symfony\Component\Form\Extension\Core\Type\TextType;
  45. use Symfony\Component\HttpFoundation\RequestStack;
  46. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  47. abstract class AbstractAdminController extends EaAbstractCrudController
  48. {
  49. protected $session;
  50. protected $request;
  51. protected $em;
  52. protected $translatorAdmin;
  53. public function __construct(
  54. SessionInterface $session,
  55. RequestStack $request,
  56. EntityManagerInterface $em,
  57. TranslatorAdmin $translatorAdmin
  58. ) {
  59. $this->session = $session;
  60. $this->request = $request;
  61. $this->em = $em;
  62. $this->translatorAdmin = $translatorAdmin;
  63. }
  64. public function configureActions(Actions $actions): Actions
  65. {
  66. /* Translatable */
  67. if ($this->isInstanceOf(TranslatableInterface::class)) {
  68. $actions->update(
  69. Crud::PAGE_INDEX,
  70. Action::EDIT,
  71. function (Action $action) {
  72. $action->setTemplatePath('@LcSov/adminlte/crud/action/translatable.html.twig');
  73. return $action;
  74. }
  75. );
  76. }
  77. /* Boutons des actions dans les listes */
  78. $actionsArray[Crud::PAGE_INDEX] = [
  79. Action::NEW => [
  80. 'icon' => 'plus',
  81. 'label' => $this->translatorAdmin->transAction('create'),
  82. 'add_class' => 'btn-sm'
  83. ],
  84. Action::EDIT => [
  85. 'class' => 'btn btn-sm btn-primary',
  86. 'icon' => 'edit',
  87. 'label' => false,
  88. 'html_attributes' => array(
  89. 'data-toggle' => 'tooltip',
  90. 'title' => $this->translatorAdmin->transAction('edit')
  91. )
  92. ],
  93. Action::DETAIL => [
  94. 'icon' => 'eye',
  95. 'add_class' => 'btn btn-success',
  96. 'label' => false,
  97. 'html_attributes' => array(
  98. 'data-toggle' => 'tooltip',
  99. 'title' => $this->translatorAdmin->transAction('detail')
  100. )
  101. ],
  102. Action::DELETE => [
  103. 'icon' => 'trash',
  104. 'dropdown' => true,
  105. 'label' => $this->translatorAdmin->transAction('delete')
  106. ],
  107. Action::BATCH_DELETE => [
  108. 'class' => 'btn btn-sm btn-danger',
  109. 'icon' => 'trash',
  110. 'label' => $this->translatorAdmin->transAction('delete')
  111. ],
  112. ];
  113. /* Boutons des actions dans l'édition */
  114. $actionSaveAndReturn = [
  115. 'add_class' => 'float-right',
  116. 'icon' => 'check',
  117. 'label' => $this->translatorAdmin->transAction('save_and_return')
  118. ];
  119. $actionIndex = [
  120. 'icon' => 'chevron-left',
  121. 'class' => 'btn btn-link',
  122. 'label' => $this->translatorAdmin->transAction('back_index')
  123. ];
  124. $actionsArray[Crud::PAGE_EDIT] = [
  125. Action::SAVE_AND_CONTINUE => [
  126. 'class' => 'btn btn-info float-right',
  127. 'label' => $this->translatorAdmin->transAction('save_and_continue')
  128. ],
  129. Action::DELETE => [
  130. 'icon' => 'trash',
  131. 'class' => 'btn btn-outline-danger action-delete',
  132. 'label' => $this->translatorAdmin->transAction('delete')
  133. ],
  134. Action::SAVE_AND_RETURN => $actionSaveAndReturn,
  135. Action::INDEX => $actionIndex,
  136. ];
  137. $actionsArray[Crud::PAGE_NEW] = [
  138. Action::SAVE_AND_ADD_ANOTHER => [
  139. 'class' => 'btn btn-info float-right',
  140. 'label' => $this->translatorAdmin->transAction('save_and_add_another')
  141. ],
  142. Action::SAVE_AND_RETURN => $actionSaveAndReturn,
  143. Action::INDEX => $actionIndex,
  144. ];
  145. $actions->add(Crud::PAGE_EDIT, Action::INDEX);
  146. $actions->add(Crud::PAGE_EDIT, Action::DELETE);
  147. $actions->add(Crud::PAGE_NEW, Action::INDEX);
  148. if ($this->isInstanceOf(SortableInterface::class)) {
  149. $sortAction = Action::new('sort', $this->translatorAdmin->transAction('sort'), 'fa fa-sort')
  150. ->linkToCrudAction('sort')
  151. ->setCssClass('btn btn-sm btn-success')
  152. ->createAsGlobalAction();
  153. $actions->add(Crud::PAGE_INDEX, $sortAction);
  154. }
  155. if ($this->isInstanceOf(TreeInterface::class)) {
  156. $indexChildAction = Action::new(
  157. 'index_children',
  158. $this->translatorAdmin->transAction('index_children'),
  159. 'fa fa-list'
  160. )
  161. ->linkToCrudAction(Action::INDEX)
  162. ->setLabel('')
  163. ->setHtmlAttributes(array('data-toggle' => 'tooltip', 'title' => 'Afficher les enfants'))
  164. ->setTemplatePath('@LcSov/adminlte/crud/action/index_children.html.twig')
  165. ->setCssClass('btn btn-sm btn-success');
  166. $backParentAction = Action::new(
  167. 'index_parent',
  168. $this->translatorAdmin->transAction('index_parent'),
  169. 'fa fa-chevron-left'
  170. )
  171. ->linkToCrudAction(Action::INDEX)
  172. ->setCssClass('btn btn-sm btn-info')
  173. ->createAsGlobalAction();
  174. $actions->add(Crud::PAGE_INDEX, $backParentAction);
  175. $actions->add(Crud::PAGE_INDEX, $indexChildAction);
  176. }
  177. $actions->reorder(Crud::PAGE_EDIT, [Action::INDEX, Action::SAVE_AND_RETURN, Action::SAVE_AND_CONTINUE]);
  178. $actions->reorder(Crud::PAGE_NEW, [Action::INDEX, Action::SAVE_AND_RETURN, Action::SAVE_AND_ADD_ANOTHER]);
  179. foreach ($actionsArray as $crudActionName => $actionsStyle) {
  180. foreach ($actionsStyle as $actionName => $button) {
  181. // si l'action existe
  182. if ($actions->getAsDto('actions')->getAction($crudActionName, $actionName)) {
  183. $actions->update(
  184. $crudActionName,
  185. $actionName,
  186. function (Action $action) use ($button) {
  187. if (isset($button['add_class'])) {
  188. $action->addCssClass($button['add_class']);
  189. }
  190. if (isset($button['class'])) {
  191. $action->setCssClass($button['class']);
  192. }
  193. if (isset($button['icon'])) {
  194. $action->setIcon('fa fa-' . $button['icon']);
  195. }
  196. if (isset($button['label'])) {
  197. $action->setLabel($button['label']);
  198. }
  199. if (isset($button['dropdown']) && $button['dropdown']) {
  200. $action->addCssClass('in-dropdown');
  201. }
  202. if (isset($button['html_attributes']) && $button['html_attributes']) {
  203. $action->setHtmlAttributes($button['html_attributes']);
  204. }
  205. return $action;
  206. }
  207. );
  208. }
  209. }
  210. }
  211. return $actions;
  212. }
  213. public function configureResponseParameters(KeyValueStore $responseParameters): KeyValueStore
  214. {
  215. if (Crud::PAGE_INDEX === $responseParameters->get('pageName')) {
  216. $responseParameters->set('fields', $this->configureFields('index'));
  217. }
  218. return $responseParameters;
  219. }
  220. public function configureCrud(Crud $crud): Crud
  221. {
  222. $crud = parent::configureCrud($crud);
  223. $this->setMaxResults($crud);
  224. if ($this->isInstanceOf(SortableInterface::class)) {
  225. $crud->setDefaultSort(['position' => 'ASC']);
  226. }
  227. return $crud;
  228. }
  229. public function setMaxResults(Crud $crud)
  230. {
  231. $entityClass = $this->getEntityFqcn();
  232. $paramListMaxResults = 'listMaxResults';
  233. $paramSessionListMaxResults = $entityClass . '-' . $paramListMaxResults;
  234. $requestListMaxResults = $this->request->getCurrentRequest()->get($paramListMaxResults);
  235. if ($requestListMaxResults) {
  236. $this->session->set($paramSessionListMaxResults, $requestListMaxResults);
  237. }
  238. $maxResults = $this->session->get($paramSessionListMaxResults) ? $this->session->get(
  239. $paramSessionListMaxResults
  240. ) : 30;
  241. $crud->setPaginatorPageSize($maxResults);
  242. }
  243. public function configureFields(string $pageName): iterable
  244. {
  245. $seoPanel = $confPanel = array();
  246. if ($this->isInstanceOf(SeoInterface::class)) {
  247. $seoPanel = [
  248. FormField::addPanel('seo')->setTemplateName('crud/field/generic'),
  249. TextField::new('metaTitle')->setLabel('Meta Title')->setHelp(
  250. 'Affiché dans les résultats de recherche Google'
  251. )->hideOnIndex(),
  252. TextareaField::new('metaDescription')->setLabel('Meta description')->setHelp(
  253. 'Affiché dans les résultats de recherche Google'
  254. )->hideOnIndex(),
  255. CollectionField::new('oldUrls')
  256. ->setFormTypeOption('entry_type', TextType::class)->setLabel(
  257. 'Anciennes urls du document'
  258. )->hideOnIndex(),
  259. ];
  260. }
  261. if ($this->isInstanceOf(DevAliasInterface::class)) {
  262. $confPanel = [
  263. FormField::addPanel('configuration')->setTemplateName('crud/field/generic'),
  264. TextField::new('devAlias')->hideOnIndex(),
  265. ];
  266. }
  267. return array_merge($seoPanel, $confPanel);
  268. }
  269. public function sort(AdminContext $context)
  270. {
  271. $event = new BeforeCrudActionEvent($context);
  272. $this->get('event_dispatcher')->dispatch($event);
  273. if ($event->isPropagationStopped()) {
  274. return $event->getResponse();
  275. }
  276. if (!$this->isGranted(Permission::EA_EXECUTE_ACTION) || !$this->isInstanceOf(SortableInterface::class)) {
  277. throw new ForbiddenActionException($context);
  278. }
  279. $fields = FieldCollection::new($this->configureFields(Crud::PAGE_INDEX));
  280. $filters = $this->get(FilterFactory::class)->create(
  281. $context->getCrud()->getFiltersConfig(),
  282. $fields,
  283. $context->getEntity()
  284. );
  285. $queryBuilder = $this->createIndexQueryBuilder($context->getSearch(), $context->getEntity(), $fields, $filters);
  286. $paginator = $this->get(PaginatorFactory::class)->create($queryBuilder);
  287. $entities = $this->get(EntityFactory::class)->createCollection($context->getEntity(), $paginator->getResults());
  288. $this->get(EntityFactory::class)->processFieldsForAll($entities, $fields);
  289. $sortableForm = $this->createFormBuilder(array('entities', $paginator->getResults()))
  290. ->add(
  291. 'entities',
  292. CollectionType::class,
  293. array(
  294. 'required' => true,
  295. 'allow_add' => true,
  296. 'entry_type' => PositionType::class,
  297. )
  298. )
  299. ->getForm();
  300. $entityManager = $this->getDoctrine()->getManagerForClass($this->getEntityFqcn());
  301. $repository = $entityManager->getRepository($this->getEntityFqcn());
  302. $sortableForm->handleRequest($context->getRequest());
  303. if ($sortableForm->isSubmitted() && $sortableForm->isValid()) {
  304. foreach ($sortableForm->get('entities')->getData() as $elm) {
  305. $entityInstance = $repository->find($elm['id']);
  306. $entityDto = $context->getEntity()->newWithInstance($entityInstance);
  307. if (!$entityDto->isAccessible()) {
  308. throw new InsufficientEntityPermissionException($context);
  309. }
  310. $event = new BeforeEntityDeletedEvent($entityInstance);
  311. $this->get('event_dispatcher')->dispatch($event);
  312. $entityInstance = $event->getEntityInstance();
  313. $entityInstance->setPosition($elm['position']);
  314. $this->updateEntity($entityManager, $entityInstance);
  315. $this->get('event_dispatcher')->dispatch(new AfterEntityUpdatedEvent($entityInstance));
  316. }
  317. $url = $this->get(AdminUrlGenerator::class)
  318. ->setAction(Action::INDEX)
  319. ->generateUrl();
  320. $this->addFlash('success', $this->translatorAdmin->transFlashMessage('sort'), array());
  321. return $this->redirect($url);
  322. }
  323. $responseParameters = $this->configureResponseParameters(
  324. KeyValueStore::new(
  325. [
  326. 'pageName' => Crud::PAGE_INDEX,
  327. 'templatePath' => '@LcSov/adminlte/crud/sort.html.twig',
  328. 'entities' => $entities,
  329. 'paginator' => $paginator,
  330. 'global_actions' => array(),
  331. 'batch_actions' => array(),
  332. 'filters' => $filters,
  333. 'sortable_form' => $sortableForm,
  334. ]
  335. )
  336. );
  337. $responseParameters->set('fields', $this->configureFields('index'));
  338. $event = new AfterCrudActionEvent($context, $responseParameters);
  339. $this->get('event_dispatcher')->dispatch($event);
  340. if ($event->isPropagationStopped()) {
  341. return $event->getResponse();
  342. }
  343. return $responseParameters;
  344. }
  345. public function createIndexQueryBuilder(
  346. SearchDto $searchDto,
  347. EntityDto $entityDto,
  348. FieldCollection $fields,
  349. FilterCollection $filters
  350. ): QueryBuilder {
  351. $queryBuilder = parent::createIndexQueryBuilder(
  352. $searchDto,
  353. $entityDto,
  354. $fields,
  355. $filters
  356. );
  357. if ($this->isInstanceOf(TreeInterface::class)) {
  358. $entityId = $searchDto->getRequest()->get('entityId');
  359. if ($entityId !== null) {
  360. $queryBuilder->andWhere('entity.parent = :entityId');
  361. $queryBuilder->setParameter('entityId', $searchDto->getRequest()->get('entityId'));
  362. } else {
  363. $queryBuilder->andWhere('entity.parent IS NULL');
  364. }
  365. }
  366. return $queryBuilder;
  367. }
  368. public function createSortQueryBuilder(
  369. SearchDto $searchDto,
  370. EntityDto $entityDto,
  371. FieldCollection $fields,
  372. FilterCollection $filters
  373. ): QueryBuilder {
  374. $queryBuilder = $this->createIndexQueryBuilder($searchDto, $entityDto, $fields, $filters);
  375. return $queryBuilder;
  376. }
  377. public function edit(AdminContext $context)
  378. {
  379. $response = parent::edit($context);;
  380. // on vide le flash bag si édition en ajax (notification déjà affichée en Javascript)
  381. if ($context->getRequest()->isXmlHttpRequest()) {
  382. $this->session->getFlashBag()->clear();
  383. }
  384. return $response;
  385. }
  386. public function isInstanceOf(string $interfaceName): bool
  387. {
  388. return in_array($interfaceName, class_implements($this->getEntityFqcn()));
  389. }
  390. public function updateEntity(EntityManagerInterface $entityManager, $entityInstance): void
  391. {
  392. $entityManager->update($entityInstance);
  393. $entityManager->flush();
  394. }
  395. public function persistEntity(EntityManagerInterface $entityManager, $entityInstance): void
  396. {
  397. $entityManager->create($entityInstance);
  398. $entityManager->flush();
  399. }
  400. }