<?php
namespace App\Controller;
use App\Entity\Gift;
use App\Entity\User;
use App\Form\GiftType;
use App\Form\UserSearchType;
use App\Form\UserType;
use App\Repository\UserRepository;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Knp\Component\Pager\PaginatorInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use App\Service\MailerService;
/**
* @Route("/user")
*/
class UserController extends AbstractController
{
/**
* @Route("/", name="user_index", methods={"GET|POST"})
* @Security("is_granted('ROLE_SUPER_ADMIN')")
*/
public function index(UserRepository $userRepository, Request $request, PaginatorInterface $paginator): Response
{
$form = $this->createForm(UserSearchType::class);
$form->handleRequest($request);
if ($form->isSubmitted()) {
$url = $this->buildSearchUrl($request->request->all());
if (!empty($url)) {
return $this->redirectToRoute('user_index', $url);
}
}
$user = new User();
$users = $paginator->paginate(
$userRepository->MyFindAll($request->query->all()), /* query NOT result */
$request->query->getInt('page', 1)/* page number */, 20/* limit per page */
);
return $this->render('user/index.html.twig', [
'users' => $users,
'list_roles' => $user->list_roles(),
'form' => $form->createView(),
]);
}
/**
* @Route("/new", name="user_new", methods={"GET","POST"})
* @Security("is_granted('ROLE_SUPER_ADMIN')")
*/
public function new(Request $request, UserPasswordHasherInterface $hasher): Response
{
$type_form = 'add';
$user = new User();
$form = $this->createForm(UserType::class, $user, ['type_form' => $type_form]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$data = $request->request->all();
$user->setPassword($hasher->hashPassword($user,$data['user']['password']));
$user->setRoles([$user->getRole()]);
$entityManager->persist($user);
$entityManager->flush();
$this->addFlash("success", "Utilisateur Ajouté avec succès");
return $this->redirectToRoute('user_index');
}
return $this->render('user/new.html.twig', [
'user' => $user,
'form' => $form->createView(),
'type_form' => $type_form
]);
}
/**
* @Route("/mot-de-passe-oublie", name="mot_de_passe_oublier", methods={"GET","POST"})
*/
public function motDePasseOublier(Request $request,MailerService $mailer, UserRepository $userRepository): Response
{
$error = false;
$message = "";
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
if ($request->request->get('email')) {
$user = $userRepository->findOneByEmail($request->request->get('email'));
if (is_null($user)) {
$error = true;
$message = "Cet email n'est pas inscrit dans notre base de données!";
} elseif (!$user->getActive()) {
$error = true;
$message = "Votre compte est bloqué ou n'a pas encore été activé";
} else {
$user->setToken($user->generateRandom());
$em->flush();
$mailer->sendHTMLEmailWithTemplate(
$this->getParameter('sender_address'), $user->getEmail(), "Mot de passe oublié", ['token' => $user->getToken()], 'emails/mot-de-passe.html.twig'
);
return $this->redirectToRoute('app_login');
}
} else {
$error = true;
$message = "Veuillez saisir un email valide!";
}
}
return $this->render('user/mot_de_passe_oublier.html.twig', ['message' => $message,
'error' => $error]);
}
/**
* @Route("/nouveau-mot-de-passe", name="user_admin_password_lost_change", methods="GET|POST")
*/
public function changePassword(Request $request, UserRepository $ur, UserPasswordEncoderInterface $encoder): Response {
$em = $this->getDoctrine()->getManager();
$token = $request->query->get('token');
/*
* Token_bahaviour
* 0- display error message
* 1- display form
* 2- display success message
*/
$token_behaviour = 0;
if ($token != "") {
$user = $ur->findOneBy([
'token' => $token,
'active' => true
]);
if (!is_null($user)) {
$token_behaviour = 1;
}
}
if ($request->isMethod('POST')) {
$pwd1 = $request->request->get('new-pass-word');
$pwd2 = $request->request->get('confirm-pass-word');
if (!$this->checIfValidPassword($pwd1)) {
$this->addFlash("danger", "Veuillez saisir un nouveau mot de passe");
} elseif ($pwd1 != $pwd2) {
$this->addFlash("danger", "Veuillez vérifier la saisie du mot de passe");
} else {
$user->setPassword($encoder->encodePassword($user, $pwd1));
$user->setToken('');
$em->persist($user);
$em->flush();
$token_behaviour = 2;
}
}
return $this->render('user/modifier_mot_passe.html.twig', [
'token_behaviour' => $token_behaviour,
'token' => $token
]);
}
/**
* @Route("/{id}/delete-confirmation", name="user_delete_confirmation", methods={"GET"})
* @Security("is_granted('ROLE_SUPER_ADMIN')")
*/
public function deleteConfirmation(User $user): Response
{
return $this->render('user/_delete_confirmation.html.twig', [
'user' => $user,
]);
}
/**
* @Route("/delete-validation", name="user_delete_validation", methods={"GET"})
* @Security("is_granted('ROLE_SUPER_ADMIN')")
*/
public function deleteValidation(): Response
{
return $this->render('user/_delete_validation.html.twig', [
]);
}
/**
* @Route("/mon-profil", name="user_profile", methods={"GET","POST"})
* @Security("is_granted('ROLE_USER')")
*/
public function profil(UserRepository $userRepository): Response
{
$user = $userRepository->findOneById($this->getUser()->getId());
return $this->render('user/profile.html.twig', [
'user' => $user,
'list_roles' => $user->list_roles(),
]);
}
/**
* @Route("/{id}", name="user_show", methods={"GET","POST"})
* @Security("is_granted('ROLE_SUPER_ADMIN')")
*/
public function show(User $user, Request $request): Response
{
$entityManager = $this->getDoctrine()->getManager();
$date = new \DateTime('now');
$gift = new Gift();
$gift->setDate($date);
$formGift = $this->createForm(GiftType::class, $gift);
$formGift->handleRequest($request);
if ($formGift->isSubmitted() && $formGift->isValid()) {
$gift->setUser($user);
$entityManager->persist($gift);
$entityManager->flush();
$this->addFlash("success", "Nouvelle configuration points fidélité ajoutés avec succès");
return $this->redirectToRoute('user_show', [
'id' => $user->getId()
]);
}
return $this->render('user/show.html.twig', [
'user' => $user,
'list_roles' => $user->list_roles(),
'formGift' => $formGift->createView(),
]);
}
/**
* @Route("/{id}/edit", name="user_edit", methods={"GET","POST"})
* @Security("is_granted('ROLE_SUPER_ADMIN')")
*/
public function edit(Request $request, UserPasswordHasherInterface $hasher, User $user): Response
{
$type_form = 'edit';
$form = $this->createForm(UserType::class, $user, ['type_form' => $type_form]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $request->request->all();
if (!empty($data['user']['password_edit'])) {
$user->setPassword($hasher->hashPassword($user,$data['user']['password_edit']));
}
$user->setRoles([$user->getRole()]);
$this->getDoctrine()->getManager()->flush();
$this->addFlash("success", "Utilisateur modifié avec succès");
return $this->redirectToRoute('user_index');
}
return $this->render('user/edit.html.twig', [
'user' => $user,
'form' => $form->createView(),
'type_form' => $type_form
]);
}
/**
* @Route("/{id}/delete", name="user_delete", methods={"DELETE"})
* @Security("is_granted('ROLE_SUPER_ADMIN')")
*/
public function delete(Request $request, User $user, EntityManagerInterface $entityManager, UserRepository $userRepository): Response
{
foreach($user->getClients() as $client){
$client->setUser(null);
$entityManager->flush();
}
foreach($user->getPieces() as $piece){
$piece->setUser(null);
$entityManager->flush();
}
$entityManager->clear();
$u = $userRepository->findOneById($user->getId());
if ($this->isCsrfTokenValid('delete'.$user->getId(), $request->request->get('_token'))) {
$entityManager->remove($u);
$entityManager->flush();
}
return $this->redirectToRoute('user_delete_validation');
}
/**
* @Route("/{id}/supprimer-configuration-fidelite-utilisateur", name="user_delete_config_gift", methods={"GET"})
* @Security("is_granted('ROLE_USER')")
*/
public function deleteConfigGift(Gift $gift): Response
{
$user_id = $gift->getUser()->getId();
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($gift);
$entityManager->flush();
$this->addFlash("success", "Configuration points fidélité supprimée avec succès");
return $this->redirectToRoute('user_show', [
'id' => $user_id
]);
}
/**
* @param $pwd
* @return bool
*/
private function checIfValidPassword($pwd) {
if (strlen($pwd) < 1) {
return false;
}
return true;
}
private function buildSearchUrl($data)
{
$url = [];
foreach ($data as $k => $v) {
if (isset($data['user_search']['name']) && !empty($data['user_search']['name'])) {
$url['name'] = $data['user_search']['name'];
}
if (isset($data['user_search']['email']) && !empty($data['user_search']['email'])) {
$url['email'] = $data['user_search']['email'];
}
if (isset($data['user_search']['active']) && $data['user_search']['active'] != '') {
$url['active'] = $data['user_search']['active'];
}
}
return $url;
}
}