Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
56 / 56
100.00% covered (success)
100.00%
5 / 5
CRAP
100.00% covered (success)
100.00%
1 / 1
UserController
100.00% covered (success)
100.00%
56 / 56
100.00% covered (success)
100.00%
5 / 5
19
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 usersListAction
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 userCreateAction
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
4
 userEditAction
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
1 / 1
11
 userDeleteAction
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2
3namespace App\Controller;
4
5use App\Entity\User;
6use App\Form\UserType;
7use Doctrine\ORM\EntityManagerInterface;
8use Symfony\Component\HttpFoundation\Request;
9use Symfony\Component\HttpFoundation\Response;
10use Symfony\Component\Routing\Annotation\Route;
11use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
12use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
13
14class UserController extends AbstractController
15{
16    private UserPasswordHasherInterface $encoder;
17
18    public function __construct(UserPasswordHasherInterface $encoder)
19    {
20        $this->encoder = $encoder;
21    }
22
23    /**
24     * Retrieves a list of users.
25     *
26     * @param EntityManagerInterface $emi The entity manager interface.
27     * @return Response The response object.
28     *
29     */
30    #[Route('/users', name: 'app_users_list', methods: ['GET'])]
31    public function usersListAction(EntityManagerInterface $emi): Response
32    {
33        // if (!$this->isGranted('ROLE_ADMIN')) {
34        //     $this->addFlash('danger', 'Vous n\'avez pas les droits pour accéder à cette page.');
35        //     return $this->redirectToRoute('app_homepage');
36        // }
37
38        return $this->render('user/list.html.twig', [
39            'controller_name' => 'UserController',
40            'users' => $emi->getRepository(User::class)->findAll()
41        ]);
42    }
43
44
45
46    /**
47     * Creates a new user.
48     *
49     * This method is responsible for creating a new user and persisting it to the database.
50     * It handles the form submission and validation, sets the user's password and roles,
51     * and redirects the user to the appropriate page based on their role.
52     *
53     * @param EntityManagerInterface $emi     The entity manager interface.
54     * @param Request                $request The request object.
55     *
56     * @return Response The response object.
57     */
58    #[Route('/users/create', name: 'app_user_create', methods: ['GET', 'POST'])]
59    public function userCreateAction(EntityManagerInterface $emi, Request $request): Response
60    {
61        // if (!$this->isGranted('ROLE_ADMIN')) {
62        //     $this->addFlash('danger', 'Vous n\'avez pas les droits pour accéder à cette page.');
63        //     return $this->redirectToRoute('app_homepage');
64        // }
65
66        $user = new User();
67        $form = $this->createForm(UserType::class, $user);
68
69        $form->handleRequest($request);
70
71        if ($form->isSubmitted() && $form->isValid()) {
72            $user = $form->getData();
73
74            $password = $this->encoder->hashPassword($user, $user->getPassword());
75            $user->setPassword($password)
76                ->setRoles(['ROLE_USER']);
77
78            $emi->persist($user);
79            $emi->flush();
80
81            $this->addFlash('success', 'L\'utilisateur a bien été ajouté.');
82
83            // if connected user is admin, redirect to admin page
84            return $this->isGranted('ROLE_ADMIN') ?
85                $this->redirectToRoute('app_admin') : $this->redirectToRoute('app_login');
86        }
87
88        return $this->render('user/create.html.twig', [
89            'controller_name' => 'UserController',
90            'form' => $form->createView(),
91        ]);
92    }
93
94
95
96    /**
97     * Edit a user.
98     *
99     * This method allows editing a user's information, such as username, email, and password.
100     * Only authenticated users can access this page. If the user is not logged in,
101     * they will be redirected to the homepage.
102     * If the user is not an admin and is trying to edit another user's information,
103     * they will be redirected to the homepage.
104     * After successfully editing the user, the user will be logged out and redirected to the
105     * admin page if they are an admin,
106     * or to the login page if they are a regular user.
107     *
108     * @param User $user The user to edit.
109     * @param Request $request The request object.
110     * @param EntityManagerInterface $emi The entity manager.
111     * @return Response The response object.
112     */
113    #[Route('/users/{id}/edit', name: 'app_user_edit', methods: ['GET', 'POST'])]
114    public function userEditAction(User $user, Request $request, EntityManagerInterface $emi): Response
115    {
116        if (!$this->getUser()) {
117            $this->addFlash('danger', 'Vous devez être connecté pour accéder à cette page.');
118            return $this->redirectToRoute('app_homepage');
119        } else {
120            if (!$this->isGranted('ROLE_ADMIN') &&  $user != $this->getUser()) {
121                $this->addFlash('danger', 'Vous n\'avez pas les droits pour accéder à cette page.');
122                return $this->redirectToRoute('app_homepage');
123            }
124
125            $form = $this->createForm(UserType::class, $user);
126
127            $form->handleRequest($request);
128
129            if ($form->isSubmitted() && $form->isValid()) {
130                if (!empty($form->get('username')->getData())) {
131                    $user->setUsername($form->get('username')->getData());
132                }
133
134                if (!empty($form->get('email')->getData())) {
135                    $user->setEmail($form->get('email')->getData());
136                }
137
138                if (!empty($form->get('password')->getData())) {
139                    $password = $this->encoder->hashPassword($user, $user->getPassword());
140                    $user->setPassword($password);
141                }
142
143                if (!$form->get('roles')->getData()) {
144                    $user->setRoles(['ROLE_USER']);
145                }
146
147                $emi->flush();
148
149                $this->addFlash('success', 'L\'utilisateur a bien été modifié. Veuillez vous reconnecter.');
150
151                return $this->isGranted('ROLE_ADMIN') ?
152                    $this->redirectToRoute('app_admin') : $this->redirectToRoute('app_login');
153            }
154
155            return $this->render('user/edit.html.twig', [
156                'controller_name' => 'UserController',
157                'form' => $form->createView(),
158                'user' => $user
159            ]);
160        }
161    }
162
163    /**
164     * Deletes a user.
165     *
166     * This method is used to delete a user from the system. Only users with the ROLE_ADMIN role
167     * are allowed to perform this action.
168     *
169     * @param User $user The user to be deleted.
170     * @param EntityManagerInterface $emi The entity manager interface.
171     * @return Response The response object.
172     *
173     */
174    #[Route('/users/{id}/delete', name: 'app_user_delete', methods: ['GET', 'DELETE'])]
175    public function userDeleteAction(User $user, EntityManagerInterface $emi): Response
176    {
177        if (!$this->isGranted('ROLE_ADMIN')) {
178            $this->addFlash('danger', 'Vous n\'avez pas les droits pour supprimer un utilisateur.');
179            return $this->redirectToRoute('app_homepage');
180        }
181
182        $emi->remove($user);
183        $emi->flush();
184
185        $this->addFlash('success', 'L\'utilisateur a bien été supprimé.');
186
187        return $this->redirectToRoute('app_admin');
188    }
189}