Completed
Push — master ( 06c1ce...67d37c )
by Jeroen
06:20
created

Controller/UsersController.php (2 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace Kunstmaan\UserManagementBundle\Controller;
4
5
use Doctrine\ORM\EntityManager;
6
use FOS\UserBundle\Event\UserEvent;
7
use FOS\UserBundle\Model\UserInterface;
8
use Kunstmaan\AdminBundle\Controller\BaseSettingsController;
9
use Kunstmaan\AdminBundle\Entity\BaseUser;
10
use Kunstmaan\AdminBundle\Event\AdaptSimpleFormEvent;
11
use Kunstmaan\AdminBundle\Event\Events;
12
use Kunstmaan\AdminBundle\FlashMessages\FlashTypes;
13
use Kunstmaan\AdminBundle\Form\RoleDependentUserFormInterface;
14
use Kunstmaan\AdminListBundle\AdminList\AdminList;
15
use Kunstmaan\UserManagementBundle\Event\UserEvents;
16
use Symfony\Component\Routing\Annotation\Route;
17
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
18
use Symfony\Component\HttpFoundation\RedirectResponse;
19
use Symfony\Component\HttpFoundation\Request;
20
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
21
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
22
23
/**
24
 * Settings controller handling everything related to creating, editing, deleting and listing users in an admin list
25
 */
26
class UsersController extends BaseSettingsController
27
{
28
    /**
29
     * List users
30
     *
31
     * @Route("/", name="KunstmaanUserManagementBundle_settings_users")
32
     * @Template("@KunstmaanAdminList/Default/list.html.twig")
33
     *
34
     * @param \Symfony\Component\HttpFoundation\Request $request
35
     *
36
     * @return array
37
     */
38
    public function listAction(Request $request)
39
    {
40
        $this->denyAccessUnlessGranted('ROLE_SUPER_ADMIN');
41
42
        $em = $this->getDoctrine()->getManager();
43
        $configuratorClassName = '';
44
        if ($this->container->hasParameter('kunstmaan_user_management.user_admin_list_configurator.class')) {
45
            $configuratorClassName = $this->container->getParameter(
46
                'kunstmaan_user_management.user_admin_list_configurator.class'
47
            );
48
        }
49
50
        $configurator = new $configuratorClassName($em);
51
52
        /* @var AdminList $adminList */
53
        $adminList = $this->container->get('kunstmaan_adminlist.factory')->createList($configurator);
54
        $adminList->bindRequest($request);
55
56
        return array(
57
            'adminlist' => $adminList,
58
        );
59
    }
60
61
    /**
62
     * Get an instance of the admin user class.
63
     *
64
     * @return BaseUser
65
     */
66
    private function getUserClassInstance()
67
    {
68
        $userClassName = $this->container->getParameter('fos_user.model.user.class');
69
70
        return new $userClassName();
71
    }
72
73
    /**
74
     * Add a user
75
     *
76
     * @Route("/add", name="KunstmaanUserManagementBundle_settings_users_add", methods={"GET", "POST"})
77
     * @Template("@KunstmaanUserManagement/Users/add.html.twig")
78
     *
79
     * @param \Symfony\Component\HttpFoundation\Request $request
80
     *
81
     * @return array
82
     */
83
    public function addAction(Request $request)
84
    {
85
        $this->denyAccessUnlessGranted('ROLE_SUPER_ADMIN');
86
87
        $user = $this->getUserClassInstance();
88
89
        $options = array('password_required' => true, 'langs' => $this->container->getParameter('kunstmaan_admin.admin_locales'), 'validation_groups' => array('Registration'), 'data_class' => \get_class($user));
90
        $formTypeClassName = $user->getFormTypeClass();
91
        $formType = new $formTypeClassName();
92
93
        if ($formType instanceof RoleDependentUserFormInterface) {
94
            // to edit groups and enabled the current user should have ROLE_SUPER_ADMIN
95
            $options['can_edit_all_fields'] = $this->isGranted('ROLE_SUPER_ADMIN');
96
        }
97
98
        $form = $this->createForm(
99
            $formTypeClassName,
100
            $user,
101
            $options
102
        );
103
104
        if ($request->isMethod('POST')) {
105
            $form->handleRequest($request);
106 View Code Duplication
            if ($form->isSubmitted() && $form->isValid()) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
107
                $user->setPasswordChanged(true);
108
                /* @var UserManager $userManager */
109
                $userManager = $this->container->get('fos_user.user_manager');
110
                $userManager->updateUser($user, true);
111
112
                $this->addFlash(
113
                    FlashTypes::SUCCESS,
114
                    $this->container->get('translator')->trans('kuma_user.users.add.flash.success.%username%', [
115
                        '%username%' => $user->getUsername(),
116
                    ])
117
                );
118
119
                return new RedirectResponse($this->generateUrl('KunstmaanUserManagementBundle_settings_users'));
120
            }
121
        }
122
123
        return array(
124
            'form' => $form->createView(),
125
        );
126
    }
127
128
    /**
129
     * Edit a user
130
     *
131
     * @param int $id
132
     *
133
     * @Route("/{id}/edit", requirements={"id" = "\d+"}, name="KunstmaanUserManagementBundle_settings_users_edit", methods={"GET", "POST"})
134
     * @Template("@KunstmaanUserManagement/Users/edit.html.twig")
135
     *
136
     * @throws AccessDeniedException
137
     *
138
     * @return array
139
     */
140
    public function editAction(Request $request, $id)
141
    {
142
        // The logged in user should be able to change his own password/username/email and not for other users
143
        if ($id == $this->container->get('security.token_storage')->getToken()->getUser()->getId()) {
144
            $requiredRole = 'ROLE_ADMIN';
145
        } else {
146
            $requiredRole = 'ROLE_SUPER_ADMIN';
147
        }
148
        $this->denyAccessUnlessGranted($requiredRole);
149
150
        /* @var EntityManager $em */
151
        $em = $this->getDoctrine()->getManager();
152
153
        /** @var UserInterface $user */
154
        $user = $em->getRepository($this->container->getParameter('fos_user.model.user.class'))->find($id);
155
        if ($user === null) {
156
            throw new NotFoundHttpException(sprintf('User with ID %s not found', $id));
157
        }
158
159
        $userEvent = new UserEvent($user, $request);
160
        $this->container->get('event_dispatcher')->dispatch(UserEvents::USER_EDIT_INITIALIZE, $userEvent);
161
162
        $options = array('password_required' => false, 'langs' => $this->container->getParameter('kunstmaan_admin.admin_locales'), 'data_class' => \get_class($user));
163
        $formFqn = $user->getFormTypeClass();
164
        $formType = new $formFqn();
165
166
        if ($formType instanceof RoleDependentUserFormInterface) {
167
            // to edit groups and enabled the current user should have ROLE_SUPER_ADMIN
168
            $options['can_edit_all_fields'] = $this->isGranted('ROLE_SUPER_ADMIN');
169
        }
170
171
        $event = new AdaptSimpleFormEvent($request, $formFqn, $user, $options);
172
        $event = $this->container->get('event_dispatcher')->dispatch(Events::ADAPT_SIMPLE_FORM, $event);
173
        $tabPane = $event->getTabPane();
174
175
        $form = $this->createForm($formFqn, $user, $options);
176
177
        if ($request->isMethod('POST')) {
178
            if ($tabPane) {
179
                $tabPane->bindRequest($request);
180
                $form = $tabPane->getForm();
181
            } else {
182
                $form->handleRequest($request);
183
            }
184
185 View Code Duplication
            if ($form->isSubmitted() && $form->isValid()) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
186
                /* @var UserManager $userManager */
187
                $userManager = $this->container->get('fos_user.user_manager');
188
                $userManager->updateUser($user, true);
189
190
                $this->addFlash(
191
                    FlashTypes::SUCCESS,
192
                    $this->container->get('translator')->trans('kuma_user.users.edit.flash.success.%username%', [
193
                        '%username%' => $user->getUsername(),
194
                    ])
195
                );
196
197
                return new RedirectResponse(
198
                    $this->generateUrl(
199
                        'KunstmaanUserManagementBundle_settings_users_edit',
200
                        array('id' => $id)
201
                    )
202
                );
203
            }
204
        }
205
206
        $params = array(
207
            'form' => $form->createView(),
208
            'user' => $user,
209
        );
210
211
        if ($tabPane) {
212
            $params = array_merge($params, array('tabPane' => $tabPane));
213
        }
214
215
        return $params;
216
    }
217
218
    /**
219
     * Delete a user
220
     *
221
     * @param Request $request
222
     * @param int     $id
223
     *
224
     * @Route("/{id}/delete", requirements={"id" = "\d+"}, name="KunstmaanUserManagementBundle_settings_users_delete", methods={"POST"})
225
     *
226
     * @throws AccessDeniedException
227
     *
228
     * @return array
229
     */
230
    public function deleteAction(Request $request, $id)
231
    {
232
        $this->denyAccessUnlessGranted('ROLE_SUPER_ADMIN');
233
234
        /* @var EntityManager $em */
235
        $em = $this->getDoctrine()->getManager();
236
        /* @var UserInterface $user */
237
        $user = $em->getRepository($this->container->getParameter('fos_user.model.user.class'))->find($id);
238
        if (!\is_null($user)) {
239
            $userEvent = new UserEvent($user, $request);
240
            $this->container->get('event_dispatcher')->dispatch(UserEvents::USER_DELETE_INITIALIZE, $userEvent);
241
242
            $em->remove($user);
243
            $em->flush();
244
245
            $this->addFlash(
246
                FlashTypes::SUCCESS,
247
                $this->container->get('translator')->trans('kuma_user.users.delete.flash.success.%username%', [
248
                    '%username%' => $user->getUsername(),
249
                ])
250
            );
251
        }
252
253
        return new RedirectResponse($this->generateUrl('KunstmaanUserManagementBundle_settings_users'));
254
    }
255
256
    /**
257
     * @return \Symfony\Component\HttpFoundation\Response
258
     */
259
    public function changePasswordAction()
260
    {
261
        // Redirect to current user edit route...
262
        return new RedirectResponse(
263
            $this->generateUrl(
264
                'KunstmaanUserManagementBundle_settings_users_edit',
265
                array(
266
                    'id' => $this->container->get('security.token_storage')->getToken()->getUser()->getId(),
267
                )
268
            )
269
        );
270
    }
271
}
272