src/Controller/UserController.php line 92

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Gift;
  4. use App\Entity\User;
  5. use App\Form\GiftType;
  6. use App\Form\UserSearchType;
  7. use App\Form\UserType;
  8. use App\Repository\UserRepository;
  9. use Doctrine\ORM\EntityManager;
  10. use Doctrine\ORM\EntityManagerInterface;
  11. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\Response;
  14. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  15. use Symfony\Component\Routing\Annotation\Route;
  16. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  17. use Knp\Component\Pager\PaginatorInterface;
  18. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
  19. use App\Service\MailerService;
  20. /**
  21.  * @Route("/user")
  22.  */
  23. class UserController extends AbstractController
  24. {
  25.     /**
  26.      * @Route("/", name="user_index", methods={"GET|POST"})
  27.      * @Security("is_granted('ROLE_SUPER_ADMIN')")
  28.      */
  29.     public function index(UserRepository $userRepositoryRequest $requestPaginatorInterface $paginator): Response
  30.     {
  31.         $form $this->createForm(UserSearchType::class);
  32.         $form->handleRequest($request);
  33.         if ($form->isSubmitted()) {
  34.             $url $this->buildSearchUrl($request->request->all());
  35.             if (!empty($url)) {
  36.                 return $this->redirectToRoute('user_index'$url);
  37.             }
  38.         }
  39.         $user = new User();
  40.         $users $paginator->paginate(
  41.             $userRepository->MyFindAll($request->query->all()), /* query NOT result */
  42.             $request->query->getInt('page'1)/* page number */20/* limit per page */
  43.         );
  44.         return $this->render('user/index.html.twig', [
  45.             'users' => $users,
  46.             'list_roles' => $user->list_roles(),
  47.             'form' => $form->createView(),
  48.         ]);
  49.     }
  50.     /**
  51.      * @Route("/new", name="user_new", methods={"GET","POST"})
  52.      * @Security("is_granted('ROLE_SUPER_ADMIN')")
  53.      */
  54.     public function new(Request $requestUserPasswordHasherInterface $hasher): Response
  55.     {
  56.         $type_form 'add';
  57.         $user = new User();
  58.         $form $this->createForm(UserType::class, $user, ['type_form' => $type_form]);
  59.         $form->handleRequest($request);
  60.         if ($form->isSubmitted() && $form->isValid()) {
  61.             $entityManager $this->getDoctrine()->getManager();
  62.             $data $request->request->all();
  63.             $user->setPassword($hasher->hashPassword($user,$data['user']['password']));
  64.             $user->setRoles([$user->getRole()]);
  65.             $entityManager->persist($user);
  66.             $entityManager->flush();
  67.             $this->addFlash("success""Utilisateur Ajouté avec succès");
  68.             return $this->redirectToRoute('user_index');
  69.         }
  70.         return $this->render('user/new.html.twig', [
  71.             'user' => $user,
  72.             'form' => $form->createView(),
  73.             'type_form' => $type_form
  74.         ]);
  75.     }
  76.     /**
  77.      * @Route("/mot-de-passe-oublie", name="mot_de_passe_oublier", methods={"GET","POST"})
  78.      */
  79.     public function motDePasseOublier(Request $request,MailerService $mailerUserRepository $userRepository): Response
  80.     {
  81.         $error false;
  82.         $message "";
  83.         $em $this->getDoctrine()->getManager();
  84.         if ($request->isMethod('POST')) {
  85.             if ($request->request->get('email')) {
  86.                 $user $userRepository->findOneByEmail($request->request->get('email'));
  87.                 if (is_null($user)) {
  88.                     $error true;
  89.                     $message "Cet email n'est pas inscrit dans notre base de données!";
  90.                 } elseif (!$user->getActive()) {
  91.                     $error true;
  92.                     $message "Votre compte est bloqué ou n'a pas encore été activé";
  93.                 } else {
  94.                     $user->setToken($user->generateRandom());
  95.                     $em->flush();
  96.                     $mailer->sendHTMLEmailWithTemplate(
  97.                         $this->getParameter('sender_address'), $user->getEmail(), "Mot de passe oublié", ['token' => $user->getToken()], 'emails/mot-de-passe.html.twig'
  98.                     );
  99.                     return $this->redirectToRoute('app_login');
  100.                 }
  101.             } else {
  102.                 $error true;
  103.                 $message "Veuillez saisir un email valide!";
  104.             }
  105.         }
  106.         return $this->render('user/mot_de_passe_oublier.html.twig', ['message' => $message,
  107.             'error' => $error]);
  108.     }
  109.     /**
  110.      * @Route("/nouveau-mot-de-passe", name="user_admin_password_lost_change", methods="GET|POST")
  111.      */
  112.     public function changePassword(Request $requestUserRepository $urUserPasswordEncoderInterface $encoder): Response {
  113.         $em $this->getDoctrine()->getManager();
  114.         $token $request->query->get('token');
  115.         /*
  116.          * Token_bahaviour
  117.          * 0- display error message
  118.          * 1- display form
  119.          * 2- display success message
  120.          */
  121.         $token_behaviour 0;
  122.         if ($token != "") {
  123.             $user $ur->findOneBy([
  124.                 'token' => $token,
  125.                 'active' => true
  126.             ]);
  127.             if (!is_null($user)) {
  128.                 $token_behaviour 1;
  129.             }
  130.         }
  131.         if ($request->isMethod('POST')) {
  132.             $pwd1 $request->request->get('new-pass-word');
  133.             $pwd2 $request->request->get('confirm-pass-word');
  134.             if (!$this->checIfValidPassword($pwd1)) {
  135.                 $this->addFlash("danger""Veuillez saisir un nouveau mot de passe");
  136.             } elseif ($pwd1 != $pwd2) {
  137.                 $this->addFlash("danger""Veuillez vérifier la saisie du mot de passe");
  138.             } else {
  139.                 $user->setPassword($encoder->encodePassword($user$pwd1));
  140.                 $user->setToken('');
  141.                 $em->persist($user);
  142.                 $em->flush();
  143.                 $token_behaviour 2;
  144.             }
  145.         }
  146.         return $this->render('user/modifier_mot_passe.html.twig', [
  147.             'token_behaviour' => $token_behaviour,
  148.             'token' => $token
  149.         ]);
  150.     }
  151.     /**
  152.      * @Route("/{id}/delete-confirmation", name="user_delete_confirmation", methods={"GET"})
  153.      * @Security("is_granted('ROLE_SUPER_ADMIN')")
  154.      */
  155.     public function deleteConfirmation(User $user): Response
  156.     {
  157.         return $this->render('user/_delete_confirmation.html.twig', [
  158.             'user' => $user,
  159.         ]);
  160.     }
  161.     /**
  162.      * @Route("/delete-validation", name="user_delete_validation", methods={"GET"})
  163.      * @Security("is_granted('ROLE_SUPER_ADMIN')")
  164.      */
  165.     public function deleteValidation(): Response
  166.     {
  167.         return $this->render('user/_delete_validation.html.twig', [
  168.         ]);
  169.     }
  170.     /**
  171.      * @Route("/mon-profil", name="user_profile", methods={"GET","POST"})
  172.      * @Security("is_granted('ROLE_USER')")
  173.      */
  174.     public function profil(UserRepository $userRepository): Response
  175.     {
  176.         $user $userRepository->findOneById($this->getUser()->getId());
  177.         return $this->render('user/profile.html.twig', [
  178.             'user' => $user,
  179.             'list_roles' => $user->list_roles(),
  180.         ]);
  181.     }
  182.     /**
  183.      * @Route("/{id}", name="user_show", methods={"GET","POST"})
  184.      * @Security("is_granted('ROLE_SUPER_ADMIN')")
  185.      */
  186.     public function show(User $userRequest $request): Response
  187.     {
  188.         $entityManager $this->getDoctrine()->getManager();
  189.         $date = new \DateTime('now');
  190.         $gift = new Gift();
  191.         $gift->setDate($date);
  192.         $formGift $this->createForm(GiftType::class, $gift);
  193.         $formGift->handleRequest($request);
  194.         if ($formGift->isSubmitted() && $formGift->isValid()) {
  195.             $gift->setUser($user);
  196.             $entityManager->persist($gift);
  197.             $entityManager->flush();
  198.             $this->addFlash("success""Nouvelle configuration points fidélité ajoutés avec succès");
  199.             return $this->redirectToRoute('user_show', [
  200.                 'id' => $user->getId()
  201.             ]);
  202.         }
  203.         return $this->render('user/show.html.twig', [
  204.             'user' => $user,
  205.             'list_roles' => $user->list_roles(),
  206.             'formGift' => $formGift->createView(),
  207.         ]);
  208.     }
  209.     /**
  210.      * @Route("/{id}/edit", name="user_edit", methods={"GET","POST"})
  211.      * @Security("is_granted('ROLE_SUPER_ADMIN')")
  212.      */
  213.     public function edit(Request $requestUserPasswordHasherInterface $hasherUser $user): Response
  214.     {
  215.         $type_form 'edit';
  216.         $form $this->createForm(UserType::class, $user, ['type_form' => $type_form]);
  217.         $form->handleRequest($request);
  218.         if ($form->isSubmitted() && $form->isValid()) {
  219.             $data $request->request->all();
  220.             if (!empty($data['user']['password_edit'])) {
  221.                 $user->setPassword($hasher->hashPassword($user,$data['user']['password_edit']));
  222.             }
  223.             $user->setRoles([$user->getRole()]);
  224.             $this->getDoctrine()->getManager()->flush();
  225.             $this->addFlash("success""Utilisateur modifié avec succès");
  226.             return $this->redirectToRoute('user_index');
  227.         }
  228.         return $this->render('user/edit.html.twig', [
  229.             'user' => $user,
  230.             'form' => $form->createView(),
  231.             'type_form' => $type_form
  232.         ]);
  233.     }
  234.     /**
  235.      * @Route("/{id}/delete", name="user_delete", methods={"DELETE"})
  236.      * @Security("is_granted('ROLE_SUPER_ADMIN')")
  237.      */
  238.     public function delete(Request $requestUser $userEntityManagerInterface $entityManagerUserRepository $userRepository): Response
  239.     {
  240.         foreach($user->getClients() as $client){
  241.             $client->setUser(null);
  242.             $entityManager->flush();
  243.         }
  244.         foreach($user->getPieces() as $piece){
  245.             $piece->setUser(null);
  246.             $entityManager->flush();
  247.         }
  248.         $entityManager->clear();
  249.         $u $userRepository->findOneById($user->getId());
  250.         if ($this->isCsrfTokenValid('delete'.$user->getId(), $request->request->get('_token'))) {
  251.             $entityManager->remove($u);
  252.             $entityManager->flush();
  253.         }
  254.         return $this->redirectToRoute('user_delete_validation');
  255.     }
  256.     /**
  257.      * @Route("/{id}/supprimer-configuration-fidelite-utilisateur", name="user_delete_config_gift", methods={"GET"})
  258.      * @Security("is_granted('ROLE_USER')")
  259.      */
  260.     public function deleteConfigGift(Gift $gift): Response
  261.     {
  262.         $user_id $gift->getUser()->getId();
  263.         $entityManager $this->getDoctrine()->getManager();
  264.         $entityManager->remove($gift);
  265.         $entityManager->flush();
  266.         $this->addFlash("success""Configuration points fidélité supprimée avec succès");
  267.         return $this->redirectToRoute('user_show', [
  268.             'id' => $user_id
  269.         ]);
  270.     }
  271.     /**
  272.      * @param $pwd
  273.      * @return bool
  274.      */
  275.     private function checIfValidPassword($pwd) {
  276.         if (strlen($pwd) < 1) {
  277.             return false;
  278.         }
  279.         return true;
  280.     }
  281.     private function buildSearchUrl($data)
  282.     {
  283.         $url = [];
  284.         foreach ($data as $k => $v) {
  285.             if (isset($data['user_search']['name']) && !empty($data['user_search']['name'])) {
  286.                 $url['name'] = $data['user_search']['name'];
  287.             }
  288.             if (isset($data['user_search']['email']) && !empty($data['user_search']['email'])) {
  289.                 $url['email'] = $data['user_search']['email'];
  290.             }
  291.             if (isset($data['user_search']['active']) && $data['user_search']['active'] != '') {
  292.                 $url['active'] = $data['user_search']['active'];
  293.             }
  294.         }
  295.         return $url;
  296.     }
  297. }