You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

462 satır
17KB

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