ACPUserController::setBreadcrumbs()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 20
Code Lines 13

Duplication

Lines 20
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 20
loc 20
rs 9.4285
cc 1
eloc 13
nc 1
nop 0
1
<?php
2
3
/*
4
 * (c) Jim Martens <[email protected]>
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
namespace TwoMartens\Bundle\CoreBundle\Controller;
11
12
use Doctrine\Common\Collections\ArrayCollection;
13
use Doctrine\Common\Collections\Collection;
14
use Doctrine\Common\Persistence\ObjectManager;
15
use FOS\UserBundle\Doctrine\UserManager;
16
use Symfony\Component\Form\Form;
17
use Symfony\Component\HttpFoundation\Request;
18
use Symfony\Component\HttpFoundation\Response;
19
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
20
use TwoMartens\Bundle\CoreBundle\Form\Type\UserType;
21
use TwoMartens\Bundle\CoreBundle\Model\Breadcrumb;
22
use TwoMartens\Bundle\CoreBundle\Model\Group;
23
use TwoMartens\Bundle\CoreBundle\Model\User;
24
25
/**
26
 * Manages the routes for the user system.
27
 *
28
 * @author    Jim Martens <[email protected]>
29
 * @copyright 2013-2015 Jim Martens
30
 */
31
class ACPUserController extends AbstractACPController
32
{
33
    /**
34
     * saves success state
35
     * @var boolean
36
     */
37
    private $success;
38
39
    /**
40
     * saves error state
41
     * @var boolean
42
     */
43
    private $error;
44
45
    /**
46
     * saves error message
47
     * @var string
48
     */
49
    private $errorMessage;
50
51
    /**
52
     * the current action
53
     * @var string
54
     */
55
    private $action;
56
57 View Code Duplication
    public function __construct()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
58
    {
59
        parent::__construct();
60
        $this->success = false;
61
        $this->error = false;
62
        $this->errorMessage = '';
63
        $this->action = '';
64
    }
65
66
    /**
67
     * Shows a user list.
68
     *
69
     * @return Response
70
     */
71 View Code Duplication
    public function listAction()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
72
    {
73
        $this->action = 'list';
74
75
        /** @var ObjectManager $objectManager */
76
        $objectManager = $this->get('twomartens.core.db_manager');
77
        $repository = $objectManager->getRepository('TwoMartensCoreBundle:User');
78
        $users = $repository->findAll();
79
80
        $this->assignVariables();
81
        $this->templateVariables['users'] = $users;
82
        $this->templateVariables['area']['title'] = $this->get('translator')
83
            ->trans('acp.user.list', [], 'TwoMartensCoreBundle');
84
85
        return $this->render(
86
            'TwoMartensCoreBundle:ACPUser:list.html.twig',
87
            $this->templateVariables
88
        );
89
    }
90
91
    /**
92
     * Shows the user add form.
93
     *
94
     * @param Request $request
95
     *
96
     * @return Response
97
     */
98
    public function addAction(Request $request)
99
    {
100
        $this->action = 'add';
101
102
        $this->denyAccessUnlessGranted('ROLE_ACP_TWOMARTENS.CORE_USER_ADD');
103
104
        /** @var UserManager $userManager */
105
        $userManager = $this->get('fos_user.user_manager');
106
        /** @var User $user */
107
        $user = $userManager->createUser();
108
109
        /** @var ObjectManager $objectManager */
110
        $objectManager = $this->get('twomartens.core.db_manager');
111
        $repositoryGroup = $objectManager->getRepository('TwoMartensCoreBundle:Group');
112
        /** @var Collection $groups */
113
        $groups = new ArrayCollection($repositoryGroup->findAll());
114
        $form = $this->createForm(
115
            UserType::class,
116
            $user,
117
            [
118
                'groups' => $groups
119
            ]
120
        );
121
122
        $form->handleRequest($request);
123
        $this->assignVariables();
124
125
        if ($form->isValid()) {
126
            $this->updateGroupAssignment($form, $user);
127
128
            // updates the canonical fields, the password and flushes the changes
129
            $userManager->updateUser($user);
130
131
            return $this->listAction();
132
        }
133
134
        $this->templateVariables['form'] = $form->createView();
135
        $this->templateVariables['area']['title'] = $this->get('translator')
136
            ->trans('acp.user.add', [], 'TwoMartensCoreBundle');
137
138
        return $this->render(
139
            'TwoMartensCoreBundle:ACPUser:add.html.twig',
140
            $this->templateVariables
141
        );
142
    }
143
144
    /**
145
     * Shows the user edit form.
146
     *
147
     * @param Request $request
148
     * @param string  $username
149
     *
150
     * @return Response
151
     */
152
    public function editAction(Request $request, $username)
153
    {
154
        $this->action = 'edit';
155
156
        $this->denyAccessUnlessGranted('ROLE_ACP_TWOMARTENS.CORE_USER_EDIT');
157
158
        /** @var ObjectManager $objectManager */
159
        $objectManager = $this->get('twomartens.core.db_manager');
160
        $repositoryUser = $objectManager->getRepository('TwoMartensCoreBundle:User');
161
        $repositoryGroup = $objectManager->getRepository('TwoMartensCoreBundle:Group');
162
        /** @var User $user */
163
        $user = $repositoryUser->findOneBy(['usernameCanonical' => $username]);
164
        /** @var Collection $groups */
165
        $groups = new ArrayCollection($repositoryGroup->findAll());
166
        $form = $this->createForm(
167
            UserType::class,
168
            $user,
169
            [
170
                'validation_groups' => ['Profile'],
171
                'groups' => $groups,
172
                'isAddForm' => false
173
            ]
174
        );
175
176
        $form->handleRequest($request);
177
178 View Code Duplication
        if ($form->isValid()) {
0 ignored issues
show
Duplication introduced by
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...
179
            $this->updateGroupAssignment($form, $user);
180
181
            // updates the canonical fields, the password and flushes the changes
182
            /** @var UserManager $userManager */
183
            $userManager = $this->get('fos_user.user_manager');
184
            $userManager->updateUser($user);
185
186
            // reauthenticate token to update roles
187
            /** @var TokenInterface $token */
188
            $token = $this->container->get('security.token_storage')->getToken();
189
            $token->setAuthenticated(false);
190
            $this->success = true;
191
        }
192
193
        $this->assignVariables();
194
        $this->templateVariables['form'] = $form->createView();
195
        $this->templateVariables['area']['title'] = $this->get('translator')
196
            ->trans('acp.user.edit', [], 'TwoMartensCoreBundle');
197
198
        return $this->render(
199
            'TwoMartensCoreBundle:ACPUser:edit.html.twig',
200
            $this->templateVariables
201
        );
202
    }
203
204
    /**
205
     * Deletes the user identified by the username.
206
     *
207
     * @param string $username
208
     *
209
     * @return Response
210
     */
211
    public function deleteAction($username)
212
    {
213
        $this->denyAccessUnlessGranted('ROLE_ACP_TWOMARTENS.CORE_USER_DELETE');
214
215
        /** @var ObjectManager $objectManager */
216
        $objectManager = $this->get('twomartens.core.db_manager');
217
        $repository = $objectManager->getRepository('TwoMartensCoreBundle:User');
218
        /** @var User $user */
219
        $user = $repository->findOneBy(['usernameCanonical' => $username]);
220
        /** @var User $loggedInUser */
221
        $loggedInUser = $this->getUser();
222
223
        if ($user->getUsernameCanonical() == $loggedInUser->getUsernameCanonical()) {
224
            throw $this->createAccessDeniedException('You cannot delete yourself!');
225
        }
226
227
        if (!$this->error) {
228
            /** @var UserManager $userManager */
229
            $userManager = $this->get('for_user.user_manager');
230
            $userManager->deleteUser($user);
231
        }
232
233
        return $this->listAction();
234
    }
235
236
    /**
237
     * {@inheritdoc}
238
     */
239 View Code Duplication
    protected function setBreadcrumbs()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
240
    {
241
        $userBreadcrumb = new Breadcrumb(
242
            'acp.user',
243
            $this->get('translator')->trans('acp.breadcrumb.user', [], 'TwoMartensCoreBundle')
244
        );
245
        $activeBreadcrumb = new Breadcrumb(
246
            'acp.user.user.'.$this->action,
247
            $this->get('translator')->trans(
248
                'acp.breadcrumb.user.user.'.$this->action,
249
                [],
250
                'TwoMartensCoreBundle'
251
            )
252
        );
253
        $activeBreadcrumb->activate();
254
        $this->breadcrumbs = [
255
            $userBreadcrumb,
256
            $activeBreadcrumb
257
        ];
258
    }
259
260
    /**
261
     * {@inheritdoc}
262
     */
263 View Code Duplication
    protected function assignVariables()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
264
    {
265
        $this->templateVariables = [
266
            'area' => [
267
                'showBreadcrumbs' => true
268
            ],
269
            'siteTitle' => $this->get('translator')->trans(
270
                'acp.siteTitle',
271
                ['globalTitle' => 'CoreBundle Test'],
272
                'TwoMartensCoreBundle'
273
            ),
274
            'navigation' => [
275
                'active' => 'user'
276
            ],
277
            'success' => $this->success,
278
            'error' => $this->error,
279
            'errorMessage' => $this->errorMessage
280
        ];
281
        parent::assignVariables();
282
    }
283
284
    /**
285
     * Updates the group assignment of given user.
286
     *
287
     * @param Form $form
288
     * @param User $user
289
     */
290
    private function updateGroupAssignment(Form $form, User $user)
291
    {
292
        /** @var ObjectManager $objectManager */
293
        $objectManager = $this->get('twomartens.core.db_manager');
294
        $repository = $objectManager->getRepository('TwoMartensCoreBundle:Group');
295
        /** @var Collection $groups */
296
        $groups = new ArrayCollection($repository->findAll());
297
        $submittedGroups = $form->get('groups')->getData();
298
        foreach ($groups as $group) {
299
            /** @var Group $group */
300
            if (in_array($group->getRoleName(), $submittedGroups)) {
301
                $user->addGroup($group);
302
                $group->addUser($user);
303
            } else {
304
                // don't remove user from group if he is last user and group
305
                // must not be empty
306
                if (!$group->canBeEmpty() && $group->getUsers()->count() <= 1) {
307
                    continue;
308
                }
309
                $user->removeGroup($group);
310
                $group->removeUser($user);
311
            }
312
        }
313
    }
314
}
315