Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

200 Zeilen
8.3KB

  1. <?php
  2. namespace Lc\SovBundle\Controller\User;
  3. use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use EasyCorp\Bundle\EasyAdminBundle\Collection\EntityCollection;
  6. use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
  7. use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
  8. use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
  9. use EasyCorp\Bundle\EasyAdminBundle\Config\KeyValueStore;
  10. use EasyCorp\Bundle\EasyAdminBundle\Context\AdminContext;
  11. use EasyCorp\Bundle\EasyAdminBundle\Event\AfterCrudActionEvent;
  12. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeCrudActionEvent;
  13. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityDeletedEvent;
  14. use EasyCorp\Bundle\EasyAdminBundle\Exception\EntityRemoveException;
  15. use EasyCorp\Bundle\EasyAdminBundle\Exception\ForbiddenActionException;
  16. use EasyCorp\Bundle\EasyAdminBundle\Exception\InsufficientEntityPermissionException;
  17. use EasyCorp\Bundle\EasyAdminBundle\Field\ChoiceField;
  18. use EasyCorp\Bundle\EasyAdminBundle\Field\EmailField;
  19. use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
  20. use EasyCorp\Bundle\EasyAdminBundle\Security\Permission;
  21. use Lc\SovBundle\Container\User\UserContainer;
  22. use Lc\SovBundle\Controller\AbstractAdminController;
  23. use Lc\SovBundle\Definition\ActionDefinition;
  24. use Lc\SovBundle\Definition\ApplicationDefinition;
  25. use Lc\SovBundle\Definition\RolesDefinition;
  26. use Lc\SovBundle\Definition\RolesDefinitionInterface;
  27. use Lc\SovBundle\Doctrine\EntityManager;
  28. use Lc\SovBundle\Doctrine\Extension\BlameableInterface;
  29. use Lc\SovBundle\Factory\User\UserFactory;
  30. use Lc\SovBundle\Form\User\ConfirmDeleteUserFormType;
  31. use Lc\SovBundle\Model\User\UserInterface;
  32. use Lc\SovBundle\Translation\FlashBagTranslator;
  33. use Lc\SovBundle\Translation\TranslatorAdmin;
  34. use Symfony\Component\HttpFoundation\RequestStack;
  35. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  36. abstract class UserAdminController extends AbstractAdminController
  37. {
  38. public function buildIndexActions(Actions $actions): void
  39. {
  40. parent::buildIndexActions($actions); // TODO: Change the autogenerated stub
  41. $actions->add(Crud::PAGE_INDEX, $this->getSwitchUserAction());
  42. }
  43. public function getSwitchUserAction(): Action
  44. {
  45. $switchAction = Action::new(
  46. ActionDefinition::SWITCH_USER,
  47. $this->get(TranslatorAdmin::class)->transAction(ActionDefinition::SWITCH_USER),
  48. 'fa fa-fw fa-user-secret'
  49. )
  50. ->linkToCrudAction(ActionDefinition::SWITCH_USER)
  51. ->setLabel($this->get(TranslatorAdmin::class)->transAction(ActionDefinition::SWITCH_USER))
  52. ->setCssClass('in-dropdown text-info action-confirm action_switch');
  53. return $switchAction;
  54. }
  55. public function overrideEntitiesActions(?EntityCollection $entities, string $pageName): void
  56. {
  57. parent::overrideEntitiesActions($entities, $pageName); // TODO: Change the autogenerated stub
  58. foreach ($entities as $entity) {
  59. foreach ($entity->getActions() as $action) {
  60. if ($action->getName() == ActionDefinition::SWITCH_USER) {
  61. $url = $this->generateUrl(
  62. $this->getParameter('lc_sov.homepage_route'),
  63. array('_switch_user' => $entity->getInstance()->getEmail())
  64. );
  65. $action->setLinkUrl($url);
  66. }
  67. }
  68. }
  69. }
  70. public function configureFields(string $pageName): iterable
  71. {
  72. return [
  73. EmailField::new('email'),
  74. TextField::new('lastname'),
  75. TextField::new('firstname'),
  76. ChoiceField::new('roles')
  77. ->allowMultipleChoices()
  78. ->autocomplete()
  79. ->setChoices($this->getUserContainer()->getRoleDefinition()->getRolesList())
  80. ];
  81. }
  82. public function createEntity(string $entityFqcn)
  83. {
  84. return $this->get(UserContainer::class)->getFactory()->create();
  85. }
  86. public function delete(AdminContext $context)
  87. {
  88. $entityManager = $this->getEntityManager();
  89. // Todo envisager un refactor similaire pour toutes les fonctions CRUD
  90. $eaBeforeCrudActionEventDelete = $this->eaBeforeCrudActionEventDelete($context);
  91. if (!is_null($eaBeforeCrudActionEventDelete)) {
  92. return $eaBeforeCrudActionEventDelete;
  93. }
  94. $user = $context->getEntity()->getInstance();
  95. $event = new BeforeEntityDeletedEvent($user);
  96. $this->container->get('event_dispatcher')->dispatch($event);
  97. if ($event->isPropagationStopped()) {
  98. return $event->getResponse();
  99. }
  100. $user = $event->getEntityInstance();
  101. // Creéer formulaire avec un champ confirm
  102. $confirmDeleteUserForm = $this->createForm(ConfirmDeleteUserFormType::class, null, array(
  103. 'action' => $this->getAdminUrlGenerator()->generateUrl()
  104. ));
  105. $confirmDeleteUserForm->handleRequest($context->getRequest());
  106. $entityManager->delete($user);
  107. $warningMessages = $this->getDeleteUserWarningMessageList($user);
  108. //Avant la suppression on s'assure que l'utilisateur à confirmer et qu'il n'y aucun message d'erreur
  109. if ($confirmDeleteUserForm->isSubmitted() && count($warningMessages['danger']) === 0) {
  110. //Détecter les tables qui possède des relations avec un champ qui n'existe plus
  111. //Dans le cas ci-dessous détecter les adresses lié à un utilisateur qui n'existe plus
  112. //SELECT * FROM address a LEFT OUTER JOIN user u ON(u.id=a.user_id) WHERE u.id is null
  113. try {
  114. $entityManager->flush();
  115. $this->addFlashTranslator('success', 'deleted');
  116. } catch (ForeignKeyConstraintViolationException $e) {
  117. throw new EntityRemoveException(['entity_name' => $context->getEntity()->getName(), 'message' => $e->getMessage()]);
  118. }
  119. return $this->redirect($this->getAdminUrlGenerator()->setAction(Crud::PAGE_INDEX)->setEntityId(null)->generateUrl());
  120. }else{
  121. if($confirmDeleteUserForm->isSubmitted()){
  122. $this->addFlashTranslator('error', 'cannotDelete');
  123. }
  124. }
  125. $responseParameters = $this->configureResponseParameters(KeyValueStore::new([
  126. 'pageName' => Crud::PAGE_DETAIL,
  127. 'templatePath' => '@LcSov/adminlte/crud/delete.html.twig',
  128. 'confirm_delete_user_form' => $confirmDeleteUserForm->createView(),
  129. 'global_actions' => array(),
  130. 'batch_actions' => array(),
  131. 'warning_message_list' => $warningMessages
  132. ]));
  133. $event = new AfterCrudActionEvent($context, $responseParameters);
  134. $this->get('event_dispatcher')->dispatch($event);
  135. if ($event->isPropagationStopped()) {
  136. return $event->getResponse();
  137. }
  138. return $responseParameters;
  139. }
  140. public function getDeleteUserWarningMessageList(UserInterface $user): array
  141. {
  142. $warningMessages = array();
  143. $warningMessages['danger'] = [];
  144. $warningMessages['warning'] = [];
  145. $warningMessages['info'] = [];
  146. $entityManager = $this->getEntityManager();
  147. $entityToDeleteListCount = array();
  148. $entityToDeleteListName = array();
  149. foreach ($entityManager->getUnitOfWork()->getScheduledEntityDeletions() as $entityToDelete) {
  150. if (isset($entityToDeleteListCount[(new \ReflectionClass($entityToDelete))->getShortName()])) {
  151. $entityToDeleteListCount[(new \ReflectionClass($entityToDelete))->getShortName()]++;
  152. } else {
  153. $entityToDeleteListCount[(new \ReflectionClass($entityToDelete))->getShortName()] = 1;
  154. }
  155. $entityToDeleteListName[(new \ReflectionClass($entityToDelete))->getShortName()][] = $entityToDelete->getId();
  156. }
  157. foreach ($entityToDeleteListCount as $entityName => $entityToDeleteCount) {
  158. $warningMessages['info'][] = $this->getTranslatorAdmin()->transFlashMessage(
  159. 'error',
  160. 'deleteEntityCascade',
  161. 'User',
  162. array(
  163. '%entity%' => $this->getTranslatorAdmin()->trans('entity.'.$entityName.'.label_plurial'),
  164. '%count%' => $entityToDeleteCount
  165. )
  166. );
  167. }
  168. return $warningMessages;
  169. }
  170. }