src/Controller/Security/UserController.php line 64

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Security;
  3. use App\Entity\City;
  4. use App\Entity\Region;
  5. use App\Repository\UserRepository;
  6. use App\Repository\RoleRepository;
  7. use App\Repository\SchoolRepository;
  8. use Doctrine\Common\Collections\Collection;
  9. use Doctrine\ORM\EntityManagerInterface;
  10. use Doctrine\ORM\QueryBuilder;
  11. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
  12. use Symfony\Bridge\Doctrine\Form\Type\EntityType;
  13. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  14. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  15. use Symfony\Component\HttpFoundation\RedirectResponse;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use Symfony\Component\HttpFoundation\RequestStack;
  18. use Symfony\Component\HttpFoundation\Response;
  19. use App\Entity\User;
  20. use App\Entity\Role;
  21. use App\Form\UserType;
  22. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  23. use Symfony\Component\Routing\Annotation\Route;
  24. // use Symfony\Component\Validator\Constraints\Collection;
  25. use Doctrine\ORM\PersistentCollection;
  26. use Symfony\Contracts\Translation\TranslatorInterface;
  27. #[Route('/user')]
  28. #[Security("is_granted('ROLE_ADMIN') 
  29.     or is_granted('ROLE_ADMIN_PAYS') 
  30.     or is_granted('ROLE_ADMIN_REGIONS') 
  31.     or is_granted('ROLE_DIPLOME')
  32. ")]
  33. class UserController extends AbstractController {
  34.     private EntityManagerInterface $em;
  35.     private UserRepository $userRepository;
  36.     private SchoolRepository $schoolRepository;
  37.     private RoleRepository $roleRepository;
  38.     private UserPasswordHasherInterface $hasher;
  39.     private RequestStack $requestStack;
  40.     private TranslatorInterface $translator;
  41.     public function __construct(
  42.         EntityManagerInterface      $em,
  43.         UserRepository              $userRepository,
  44.         RoleRepository              $roleRepository,
  45.         SchoolRepository $schoolRepository,
  46.         UserPasswordHasherInterface $hasher,
  47.         RequestStack                $requestStack,
  48.         TranslatorInterface $translator
  49.     ) {
  50.         $this->em $em;
  51.         $this->userRepository $userRepository;
  52.         $this->roleRepository $roleRepository;
  53.         $this->schoolRepository $schoolRepository;
  54.         $this->hasher $hasher;
  55.         $this->requestStack $requestStack;
  56.         $this->translator $translator;
  57.     }
  58.     #[Route(path'/'name'user_index'methods: ['GET'])]
  59.     public function indexAction(): Response {
  60.         $allUsers $this->userRepository->getAllUser();
  61.         $users = [];
  62.         if($this->getUser()->hasRole('ROLE_ADMIN')) {
  63.             $users $allUsers;
  64.         } else if($this->getUser()->hasRole('ROLE_ADMIN_PAYS')) {
  65.             foreach ($allUsers as $user) {
  66.                 if($user->roles() != 'ROLE_ADMIN_PAYS') {
  67.                     if ($user->country() == $this->getUser()->getCountry()->getName()) {
  68.                         $users[] = $user;
  69.                     }
  70.                 }
  71.             }
  72.         } else if($this->getUser()->hasRole('ROLE_ADMIN_REGIONS')) {
  73.             foreach ($allUsers as $user) {
  74.                 if(($user->roles() != 'ROLE_ADMIN_PAYS') && ($user->roles() != 'ROLE_ADMIN_REGIONS')) {
  75.                     $regions $this->getUser()->getAdminRegions();
  76.                     foreach ($regions as $region) {
  77.                         if ($user->region()) {
  78.                             if ($region->getName() == $user->region()) {
  79.                                 $users[] = $user;
  80.                             }
  81.                         }
  82.                     }
  83.                 }
  84.             }
  85.         }
  86.         return $this->render('user/index.html.twig', [
  87.             'users' => $users
  88.         ]);
  89.     }
  90.     #[Route(path'/new'name'user_new'methods: ['POST''GET'])]
  91.     public function newAction(Request $request): RedirectResponse|Response {
  92.         $user = new User();
  93.         // $form = $this->createForm(UserType::class, $user);
  94.         // //Adaptation for DBTA
  95.         // if($_ENV['STRUCT_PROVINCE_COUNTRY_CITY'] == 'true') {
  96.             $form $this->createForm(UserType::class, $user);
  97.         // }
  98.         $roles $this->roleRepository->findAll();
  99.         $form->handleRequest($request);
  100.         if ($form->isSubmitted() && $form->isValid()) {
  101.             //Adaptation for DBTA
  102.             if($_ENV['STRUCT_PROVINCE_COUNTRY_CITY'] == 'true') {
  103.                 if($user->getRegion()) {
  104.                     $user->setCountry($user->getRegion()->getCountry());
  105.                 } elseif (count($user->getAdminRegions())>0) {
  106.                     $user->setCountry($user->getAdminRegions()[0]->getCountry());
  107.                 }
  108.             }
  109.             //Only for Principal
  110.             if($user->hasRole(Role::ROLE_PRINCIPAL)) {
  111.                 if($user->getSchool())
  112.                     $user->setPrincipalSchool($user->getSchool()->getId());
  113.             }
  114.             $user->setPassword($this->hasher->hashPassword($user$user->getPlainPassword()));
  115.             $user->setEnabled(true);
  116.             $this->em->persist($user);
  117.             $this->em->flush();
  118.             return $this->redirectToRoute('user_show', ['id' => $user->getId()]);
  119.         }
  120.         //Change access of Roles function of current Administrator level
  121.         if($this->getUser()->hasRole('ROLE_ADMIN_PAYS')) {
  122.             $this->changeRoleFormAdminPays ($form);
  123.         } else if($this->getUser()->hasRole('ROLE_ADMIN_REGIONS')) {
  124.             $this->changeRoleFormAdminRegions ($form);
  125.         }
  126.         return $this->render('user/new.html.twig', [
  127.             'user' => $user,
  128.             'form' => $form->createView(),
  129.             'roles' => $roles
  130.         ]);
  131.     }
  132.     #[Route(path'/{id}'name'user_show'methods: ['GET'])]
  133.     public function showAction(User $user2): Response {
  134.         return $this->render('user/show.html.twig', [
  135.             'user2' => $user2
  136.         ]);
  137.     }
  138.     #[Route(path'/{id}/edit'name'user_edit'methods: ['GET''POST''PUT'])]
  139.     public function editAction(Request $requestUser $user): RedirectResponse|Response {
  140.         //Only for Principal
  141.         if($user->hasRole(Role::ROLE_PRINCIPAL)) {
  142.             if($user->getPrincipalSchool()) {
  143.                 $school $this->schoolRepository->find($user->getPrincipalSchool());
  144.                 if($school) {
  145.                     $user->setSchool($school);
  146.                 }
  147.             }
  148.         }
  149.         $editForm $this->createForm(UserType::class, $user);
  150.         $roles $this->roleRepository->findAll();
  151.         $editForm->handleRequest($request);
  152.         //Change access of Roles function of current Administrator level
  153.         if($this->getUser()->hasRole('ROLE_ADMIN_PAYS')) {
  154.             $this->changeRoleFormAdminPays ($editForm);
  155.         } else if($this->getUser()->hasRole('ROLE_ADMIN_REGIONS')) {
  156.             $this->changeRoleFormAdminRegions ($editForm);
  157.         }
  158.         if ($editForm->isSubmitted() && $editForm->isValid()) {
  159.             //Adaptation for DBTA
  160.             if($_ENV['STRUCT_PROVINCE_COUNTRY_CITY'] == 'true') {
  161.                 if($user->getRegion()) {
  162.                     $user->setCountry($user->getRegion()->getCountry());
  163.                 } elseif (count($user->getAdminRegions())>0) {
  164.                     $user->setCountry($this->getFirstRegionCityNotNull($user->getAdminRegions())->getCountry());
  165.                 } elseif (count($user->getAdminCities())>0) {
  166.                     $user->setRegion($this->getFirstRegionCityNotNull($user->getAdminCities())->getRegion());
  167.                     $user->setCountry($user->getRegion()->getCountry());
  168.                 }
  169.             }
  170.             //Only for Principal
  171.             if($user->hasRole(Role::ROLE_PRINCIPAL)) {
  172.                 if($user->getSchool())
  173.                     $user->setPrincipalSchool($user->getSchool()->getId());
  174.             }
  175.             $user->setPassword($this->hasher->hashPassword($user$user->getPlainPassword()));
  176.             $this->em->flush();
  177.             return $this->redirectToRoute('user_show', ['id' => $user->getId()]);
  178.         }
  179.         return $this->render('user/edit.html.twig', [
  180.             'user' => $user,
  181.             'edit_form' => $editForm->createView(),
  182.             'roles' => $roles
  183.         ]);
  184.     }
  185.     #[Route(path'/delete/{id}'name'user_delete'methods: ['GET'])]
  186.     public function deleteAction(Request $request, ?User $user): RedirectResponse {
  187.         if (array_key_exists('HTTP_REFERER'$request->server->all())) {
  188.             if ($user) {
  189.                 if($user->getSchool()) {
  190.                     $principals $this->userRepository->findByPrincipalSchool($user->getSchool()->getId());
  191.                     foreach ($principals as $principal) {
  192.                         $this->em->remove($principal);
  193.                         // var_dump("principal:",$principal->getId());
  194.                     }
  195.                 }
  196.                 $this->removeRelations($user);
  197.                 $this->em->remove($user);
  198.                 // var_dump("user:",$user->getId());die();
  199.                 $this->em->flush();
  200.                 $this->addFlash('success'$this->translator->trans('flashbag.the_deletion_is_done_successfully'));
  201.             } else {
  202.                 $this->addFlash('warning'$this->translator->trans('flashbag.unable_to_delete_the_country'));
  203.                 return $this->redirect($request->server->all()['HTTP_REFERER']);
  204.             }
  205.         }
  206.         return $this->redirectToRoute('user_index');
  207.     }
  208.     /**
  209.      * @param User $user
  210.      */
  211.     private function removeRelations(User $user) {
  212.         if ($user->getPersonDegree()) {
  213.             foreach ($user->getPersonDegree() as $diplome) {
  214.                 $this->em->remove($diplome);
  215.             }
  216.         }
  217.         if ($user->getCompany()) {
  218.             foreach ($user->getCompany() as $company) {
  219.                 $this->em->remove($company);
  220.             }
  221.         }
  222.         if ($user->getSchool()) {
  223.             foreach ($user->getSchool() as $school) {
  224.                 $this->em->remove($school);
  225.             }
  226.         }
  227.     }
  228.     private function changeRoleFormAdminPays ($form) {
  229.         $form->remove('profils');
  230.         $form->add('profils'EntityType::class, [
  231.             'class' => Role::class,
  232.             'multiple' => true,
  233.             'query_builder' => function (RoleRepository $r) {
  234.                 return $r->createQueryBuilder('ig')
  235.                     ->Where('ig.role = \'ROLE_ADMIN_REGIONS\'')
  236.                     ->orWhere('ig.role = \'ROLE_ADMIN_VILLES\'')
  237.                     ->orWhere('ig.role = \'ROLE_LEGISLATEUR\'')
  238.                     ->orWhere('ig.role = \'ROLE_PRINCIPAL\'');
  239.             },
  240.             'attr' => ['class' => 'form-control select2',]
  241.         ]);
  242.     }
  243.     private function changeRoleFormAdminRegions ($form) {
  244.         $form->remove('profils');
  245.         $form->add('profils'EntityType::class, [
  246.             'class' => Role::class,
  247.             'multiple' => true,
  248.             'query_builder' => function (RoleRepository $r) {
  249.                 return $r->createQueryBuilder('ig')
  250.                     ->Where('ig.role = \'ROLE_ADMIN_VILLES\'')
  251.                     ->orWhere('ig.role = \'ROLE_PRINCIPAL\'');
  252.             },
  253.             'attr' => ['class' => 'form-control select2',]
  254.         ]);
  255.     }
  256.     /**
  257.      * Fix Bug if null region store with select2 JS function
  258.      * @param Collection $collection
  259.      * @return Region|City
  260.      */
  261.     private function getFirstRegionCityNotNull (Collection $collection): Region|City {
  262.         $FirstObjectNotNull null;
  263.         for ($i $i count($collection) ; $i++) {
  264.             if($collection[$i]) {
  265.                 $FirstObjectNotNull $collection[$i];
  266.                 $i count($collection);
  267.             }
  268.         }
  269.         return $FirstObjectNotNull;
  270.     }
  271. }