Completed
Push — master ( 91fdab...75a7b9 )
by
unknown
13:37
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 Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
17
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
18
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
19
use Symfony\Component\HttpFoundation\RedirectResponse;
20
use Symfony\Component\HttpFoundation\Request;
21
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
22
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
23
24
/**
25
 * Settings controller handling everything related to creating, editing, deleting and listing users in an admin list
26
 */
27
class UsersController extends BaseSettingsController
28
{
29
    /**
30
     * List users
31
     *
32
     * @Route("/", name="KunstmaanUserManagementBundle_settings_users")
33
     * @Template("KunstmaanAdminListBundle:Default:list.html.twig")
34
     *
35
     * @param \Symfony\Component\HttpFoundation\Request $request
36
     *
37
     * @return array
38
     */
39
    public function listAction(Request $request)
40
    {
41
        $this->denyAccessUnlessGranted('ROLE_SUPER_ADMIN');
42
43
        $em = $this->getDoctrine()->getManager();
44
        $configuratorClassName = '';
45
        if ($this->container->hasParameter('kunstmaan_user_management.user_admin_list_configurator.class')) {
46
            $configuratorClassName = $this->container->getParameter(
47
                'kunstmaan_user_management.user_admin_list_configurator.class'
48
            );
49
        }
50
51
        $configurator = new $configuratorClassName($em);
52
53
        /* @var AdminList $adminList */
54
        $adminList = $this->container->get("kunstmaan_adminlist.factory")->createList($configurator);
55
        $adminList->bindRequest($request);
56
57
        return array(
58
            'adminlist' => $adminList,
59
        );
60
    }
61
62
    /**
63
     * Get an instance of the admin user class.
64
     *
65
     * @return BaseUser
66
     */
67
    private function getUserClassInstance()
68
    {
69
        $userClassName = $this->container->getParameter('fos_user.model.user.class');
70
71
        return new $userClassName();
72
    }
73
74
    /**
75
     * Add a user
76
     *
77
     * @Route("/add", name="KunstmaanUserManagementBundle_settings_users_add")
78
     * @Method({"GET", "POST"})
79
     * @Template("@KunstmaanUserManagement/Users/add.html.twig")
80
     *
81
     * @param \Symfony\Component\HttpFoundation\Request $request
82
     *
83
     * @return array
84
     */
85
    public function addAction(Request $request)
86
    {
87
        $this->denyAccessUnlessGranted('ROLE_SUPER_ADMIN');
88
89
        $user = $this->getUserClassInstance();
90
91
        $options = array('password_required' => true, 'langs' => $this->container->getParameter('kunstmaan_admin.admin_locales'), 'validation_groups' => array('Registration'), 'data_class' => get_class($user));
92
        $formTypeClassName = $user->getFormTypeClass();
93
        $formType = new $formTypeClassName();
94
95
        if ($formType instanceof RoleDependentUserFormInterface) {
96
            // to edit groups and enabled the current user should have ROLE_SUPER_ADMIN
97
            $options['can_edit_all_fields'] = $this->isGranted('ROLE_SUPER_ADMIN');
98
        }
99
100
        $form = $this->createForm(
101
            $formTypeClassName,
102
            $user,
103
            $options
104
        );
105
106
        if ($request->isMethod('POST')) {
107
            $form->handleRequest($request);
108 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...
109
                $user->setPasswordChanged(true);
110
                /* @var UserManager $userManager */
111
                $userManager = $this->container->get('fos_user.user_manager');
112
                $userManager->updateUser($user, true);
113
114
                $this->addFlash(
115
                    FlashTypes::SUCCESS,
116
                    $this->container->get('translator')->trans('kuma_user.users.add.flash.success.%username%', [
117
                        '%username%' => $user->getUsername()
118
                    ])
119
                );
120
121
                return new RedirectResponse($this->generateUrl('KunstmaanUserManagementBundle_settings_users'));
122
            }
123
        }
124
125
        return array(
126
            'form' => $form->createView(),
127
        );
128
    }
129
130
    /**
131
     * Edit a user
132
     *
133
     * @param int $id
134
     *
135
     * @Route("/{id}/edit", requirements={"id" = "\d+"}, name="KunstmaanUserManagementBundle_settings_users_edit")
136
     * @Method({"GET", "POST"})
137
     * @Template("@KunstmaanUserManagement/Users/edit.html.twig")
138
     *
139
     * @throws AccessDeniedException
140
     * @return array
141
     */
142
    public function editAction(Request $request, $id)
143
    {
144
        // The logged in user should be able to change his own password/username/email and not for other users
145
        if ($id == $this->container->get('security.token_storage')->getToken()->getUser()->getId()) {
146
            $requiredRole = 'ROLE_ADMIN';
147
        } else {
148
            $requiredRole = 'ROLE_SUPER_ADMIN';
149
        }
150
        $this->denyAccessUnlessGranted($requiredRole);
151
152
        /* @var $em EntityManager */
153
        $em = $this->getDoctrine()->getManager();
154
155
        /** @var UserInterface $user */
156
        $user = $em->getRepository($this->container->getParameter('fos_user.model.user.class'))->find($id);
157
        if ($user === null) {
158
            throw new NotFoundHttpException(sprintf('User with ID %s not found', $id));
159
        }
160
161
        $userEvent = new UserEvent($user, $request);
162
        $this->container->get('event_dispatcher')->dispatch(UserEvents::USER_EDIT_INITIALIZE, $userEvent);
163
164
        $options = array('password_required' => false, 'langs' => $this->container->getParameter('kunstmaan_admin.admin_locales'), 'data_class' => get_class($user));
165
        $formFqn = $user->getFormTypeClass();
166
        $formType = new $formFqn();
167
168
        if ($formType instanceof RoleDependentUserFormInterface) {
169
            // to edit groups and enabled the current user should have ROLE_SUPER_ADMIN
170
            $options['can_edit_all_fields'] = $this->isGranted('ROLE_SUPER_ADMIN');
171
        }
172
173
        $event = new AdaptSimpleFormEvent($request, $formFqn, $user, $options);
174
        $event = $this->container->get('event_dispatcher')->dispatch(Events::ADAPT_SIMPLE_FORM, $event);
175
        $tabPane = $event->getTabPane();
176
177
        $form = $this->createForm($formFqn, $user, $options);
178
179
        if ($request->isMethod('POST')) {
180
181
            if ($tabPane) {
182
                $tabPane->bindRequest($request);
183
                $form = $tabPane->getForm();
184
            } else {
185
                $form->handleRequest($request);
186
            }
187
188 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...
189
                /* @var UserManager $userManager */
190
                $userManager = $this->container->get('fos_user.user_manager');
191
                $userManager->updateUser($user, true);
192
193
                $this->addFlash(
194
                    FlashTypes::SUCCESS,
195
                    $this->container->get('translator')->trans('kuma_user.users.edit.flash.success.%username%', [
196
                        '%username%' => $user->getUsername()
197
                    ])
198
                );
199
200
                return new RedirectResponse(
201
                    $this->generateUrl(
202
                        'KunstmaanUserManagementBundle_settings_users_edit',
203
                        array('id' => $id)
204
                    )
205
                );
206
            }
207
        }
208
209
        $params = array(
210
            'form' => $form->createView(),
211
            'user' => $user,
212
        );
213
214
        if ($tabPane) {
215
            $params = array_merge($params, array('tabPane' => $tabPane));
216
        }
217
218
        return $params;
219
    }
220
221
    /**
222
     * Delete a user
223
     *
224
     * @param Request $request
225
     * @param int $id
226
     *
227
     * @Route("/{id}/delete", requirements={"id" = "\d+"}, name="KunstmaanUserManagementBundle_settings_users_delete")
228
     * @Method({"GET", "POST"})
229
     *
230
     * @throws AccessDeniedException
231
     * @return array
232
     */
233
    public function deleteAction(Request $request, $id)
234
    {
235
        $this->denyAccessUnlessGranted('ROLE_SUPER_ADMIN');
236
237
        /* @var $em EntityManager */
238
        $em = $this->getDoctrine()->getManager();
239
        /* @var UserInterface $user */
240
        $user = $em->getRepository($this->container->getParameter('fos_user.model.user.class'))->find($id);
241
        if (!is_null($user)) {
242
            $userEvent = new UserEvent($user, $request);
243
            $this->container->get('event_dispatcher')->dispatch(UserEvents::USER_DELETE_INITIALIZE, $userEvent);
244
245
            $em->remove($user);
246
            $em->flush();
247
248
            $this->addFlash(
249
                FlashTypes::SUCCESS,
250
                $this->container->get('translator')->trans('kuma_user.users.delete.flash.success.%username%', [
251
                    '%username%' => $user->getUsername()
252
                ])
253
            );
254
        }
255
256
        return new RedirectResponse($this->generateUrl('KunstmaanUserManagementBundle_settings_users'));
257
    }
258
259
    /**
260
     * @return \Symfony\Component\HttpFoundation\Response
261
     */
262
    public function changePasswordAction()
263
    {
264
        // Redirect to current user edit route...
265
        return new RedirectResponse(
266
            $this->generateUrl(
267
                'KunstmaanUserManagementBundle_settings_users_edit',
268
                array(
269
                    'id' => $this->container->get('security.token_storage')->getToken()->getUser()->getId(),
270
                )
271
            )
272
        );
273
    }
274
}
275