ACPGroupController   A
last analyzed

Complexity

Total Complexity 20

Size/Duplication

Total Lines 345
Duplicated Lines 23.19 %

Coupling/Cohesion

Components 1
Dependencies 10

Importance

Changes 11
Bugs 2 Features 6
Metric Value
wmc 20
c 11
b 2
f 6
lcom 1
cbo 10
dl 80
loc 345
rs 10

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 8 8 1
A listAction() 19 19 1
B addAction() 0 75 4
A editAction() 0 56 3
B deleteAction() 13 38 3
A setBreadcrumbs() 20 20 1
A assignVariables() 20 20 1
B updateOptions() 0 34 6

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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\Persistence\ObjectManager;
13
use Symfony\Component\Form\Form;
14
use Symfony\Component\HttpFoundation\Request;
15
use Symfony\Component\HttpFoundation\Response;
16
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
17
use TwoMartens\Bundle\CoreBundle\Form\Type\GroupType;
18
use TwoMartens\Bundle\CoreBundle\Group\GroupServiceInterface;
19
use TwoMartens\Bundle\CoreBundle\Model\Breadcrumb;
20
use TwoMartens\Bundle\CoreBundle\Model\Group;
21
use TwoMartens\Bundle\CoreBundle\Model\OptionCategory;
22
23
/**
24
 * Manages the routes for the group system.
25
 *
26
 * @author    Jim Martens <[email protected]>
27
 * @copyright 2013-2015 Jim Martens
28
 */
29
class ACPGroupController extends AbstractACPController
30
{
31
    /**
32
     * saves success state
33
     * @var boolean
34
     */
35
    private $success;
36
37
    /**
38
     * saves error state
39
     * @var boolean
40
     */
41
    private $error;
42
43
    /**
44
     * saves error message
45
     * @var string
46
     */
47
    private $errorMessage;
48
49
    /**
50
     * the current action
51
     * @var string
52
     */
53
    private $action;
54
55 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...
56
    {
57
        parent::__construct();
58
        $this->success = false;
59
        $this->error = false;
60
        $this->errorMessage = '';
61
        $this->action = '';
62
    }
63
64
    /**
65
     * Shows a group list.
66
     *
67
     * @return Response
68
     */
69 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...
70
    {
71
        $this->action = 'list';
72
73
        /** @var ObjectManager $objectManager */
74
        $objectManager = $this->get('twomartens.core.db_manager');
75
        $repository = $objectManager->getRepository('TwoMartensCoreBundle:Group');
76
        $groups = $repository->findAll();
77
78
        $this->assignVariables();
79
        $this->templateVariables['groups'] = $groups;
80
        $this->templateVariables['area']['title'] = $this->get('translator')
81
            ->trans('acp.group.list', [], 'TwoMartensCoreBundle');
82
83
        return $this->render(
84
            'TwoMartensCoreBundle:ACPGroup:list.html.twig',
85
            $this->templateVariables
86
        );
87
    }
88
89
    /**
90
     * Shows the group add form.
91
     *
92
     * @param Request $request
93
     *
94
     * @return Response
95
     */
96
    public function addAction(Request $request)
97
    {
98
        $this->action = 'add';
99
100
        $this->denyAccessUnlessGranted('ROLE_ACP_TWOMARTENS.CORE_GROUP_ADD');
101
102
        /** @var GroupServiceInterface $groupService */
103
        $groupService = $this->get('twomartens.core.group');
104
        // default is no real group but contains the default option values
105
        $options = $groupService->getOptionsFor('DEFAULT');
106
        $categories = $options->getCategories();
107
        $sortedCategories = [];
108
109
        foreach ($categories as $category) {
110
            $sortedCategories[$category->getName()] = $category;
111
        }
112
113
        $group = new Group(
114
            null, // no id known yet
115
            '', // no role name yet
116
            '', // no public name yet
117
            false, // all new groups created through ACP are non-essential
118
            true, // all new groups created through ACP can be empty
119
            [], // no known roles yet
120
            $sortedCategories['frontend'],
121
            $sortedCategories['mod'],
122
            $sortedCategories['acp']
123
        );
124
125
        $form = $this->createForm(
126
            GroupType::class,
127
            $group,
128
            [
129
                'validation_groups' => ['Registration', 'NewGroup'],
130
                'isEditForm' => false
131
            ]
132
        );
133
134
        $form->handleRequest($request);
135
        $this->assignVariables();
136
137
        if ($form->isValid()) {
138
            /** @var OptionCategory[] $categories */
139
            $categories = [
140
                $group->getACPCategory(),
141
                $group->getFrontendModCategory(),
142
                $group->getFrontendUserCategory()
143
            ];
144
            $roles = [];
145
            foreach ($categories as $category) {
146
                $newRoles = $this->updateOptions($category, $form);
147
                $roles = array_merge($roles, $newRoles);
148
            }
149
            // add group role
150
            $roles[] = 'ROLE_' . $group->getRoleName();
151
            $group->setRoles($roles);
152
153
            /** @var ObjectManager $objectManager */
154
            $objectManager = $this->get('twomartens.core.db_manager');
155
            $objectManager->persist($group);
156
            $groupService->commitChanges();
157
            $objectManager->flush();
158
159
            return $this->listAction();
160
        }
161
162
        $this->templateVariables['form'] = $form->createView();
163
        $this->templateVariables['area']['title'] = $this->get('translator')
164
            ->trans('acp.group.add', [], 'TwoMartensCoreBundle');
165
166
        return $this->render(
167
            'TwoMartensCoreBundle:ACPGroup:add.html.twig',
168
            $this->templateVariables
169
        );
170
    }
171
172
    /**
173
     * Shows the group edit form.
174
     *
175
     * @param Request $request
176
     * @param string  $rolename
177
     *
178
     * @return Response
179
     */
180
    public function editAction(Request $request, $rolename)
181
    {
182
        $this->action = 'edit';
183
184
        $this->denyAccessUnlessGranted('ROLE_ACP_TWOMARTENS.CORE_GROUP_EDIT');
185
186
        /** @var ObjectManager $objectManager */
187
        $objectManager = $this->get('twomartens.core.db_manager');
188
        $repository = $objectManager->getRepository('TwoMartensCoreBundle:Group');
189
        /** @var Group $group */
190
        $group = $repository->findOneBy(['roleName' => $rolename]);
191
        $form = $this->createForm(
192
            GroupType::class,
193
            $group
194
        );
195
196
        $form->handleRequest($request);
197
198
        if ($form->isValid()) {
199
            /** @var OptionCategory[] $categories */
200
            $categories = [
201
                $group->getACPCategory(),
202
                $group->getFrontendModCategory(),
203
                $group->getFrontendUserCategory()
204
            ];
205
            $roles = [];
206
            foreach ($categories as $category) {
207
                $newRoles = $this->updateOptions($category, $form);
208
                $roles = array_merge($roles, $newRoles);
209
            }
210
            // add group role
211
            $roles[] = 'ROLE_' . $group->getRoleName();
212
            $group->setRoles($roles);
213
214
            $objectManager->flush();
215
            /** @var GroupServiceInterface $groupService */
216
            $groupService = $this->get('twomartens.core.group');
217
            $groupService->commitChanges();
218
219
            // reauthenticate token to update roles
220
            /** @var TokenInterface $token */
221
            $token = $this->container->get('security.token_storage')->getToken();
222
            $token->setAuthenticated(false);
223
            $this->success = true;
224
        }
225
226
        $this->assignVariables();
227
        $this->templateVariables['form'] = $form->createView();
228
        $this->templateVariables['area']['title'] = $this->get('translator')
229
            ->trans('acp.group.edit', [], 'TwoMartensCoreBundle');
230
231
        return $this->render(
232
            'TwoMartensCoreBundle:ACPGroup:edit.html.twig',
233
            $this->templateVariables
234
        );
235
    }
236
237
    /**
238
     * Deletes the group identified by the role name.
239
     *
240
     * @param string $rolename
241
     *
242
     * @return Response
243
     */
244
    public function deleteAction($rolename)
245
    {
246
        $this->denyAccessUnlessGranted('ROLE_ACP_TWOMARTENS.CORE_GROUP_DELETE');
247
248
        /** @var ObjectManager $objectManager */
249
        $objectManager = $this->get('twomartens.core.db_manager');
250
        $repository = $objectManager->getRepository('TwoMartensCoreBundle:Group');
251
        /** @var Group $group */
252
        $group = $repository->findOneBy(['roleName' => $rolename]);
253
254
        // perform validation - to be sure
255
        if ($group->isEssential()) {
256
            $this->error = true;
257
            $this->errorMessage = $this->get('translator')->trans(
258
                'acp.group.delete.error.essential',
259
                [
260
                    'name' => $group->getPublicName()
261
                ],
262
                'TwoMartensCoreBundle'
263
            );
264
        }
265
266 View Code Duplication
        if (!$this->error) {
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...
267
            /** @var GroupServiceInterface $groupService */
268
            $groupService = $this->get('twomartens.core.group');
269
            $objectManager->remove($group);
270
            $groupService->commitChanges();
271
            $objectManager->flush();
272
273
            // reauthenticate token to update roles
274
            /** @var TokenInterface $token */
275
            $token = $this->container->get('security.token_storage')->getToken();
276
            $token->setAuthenticated(false);
277
            $this->success = true;
278
        }
279
280
        return $this->listAction();
281
    }
282
283
    /**
284
     * {@inheritdoc}
285
     */
286 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...
287
    {
288
        $userBreadcrumb = new Breadcrumb(
289
            'acp.user',
290
            $this->get('translator')->trans('acp.breadcrumb.user', [], 'TwoMartensCoreBundle')
291
        );
292
        $activeBreadcrumb = new Breadcrumb(
293
            'acp.user.group.'.$this->action,
294
            $this->get('translator')->trans(
295
                'acp.breadcrumb.user.group.'.$this->action,
296
                [],
297
                'TwoMartensCoreBundle'
298
            )
299
        );
300
        $activeBreadcrumb->activate();
301
        $this->breadcrumbs = [
302
            $userBreadcrumb,
303
            $activeBreadcrumb
304
        ];
305
    }
306
307
    /**
308
     * {@inheritdoc}
309
     */
310 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...
311
    {
312
        $this->templateVariables = [
313
            'area' => [
314
                'showBreadcrumbs' => true
315
            ],
316
            'siteTitle' => $this->get('translator')->trans(
317
                'acp.siteTitle',
318
                ['globalTitle' => 'CoreBundle Test'],
319
                'TwoMartensCoreBundle'
320
            ),
321
            'navigation' => [
322
                'active' => 'user'
323
            ],
324
            'success' => $this->success,
325
            'error' => $this->error,
326
            'errorMessage' => $this->errorMessage
327
        ];
328
        parent::assignVariables();
329
    }
330
331
    /**
332
     * Updates the options of the given category and returns the roles.
333
     *
334
     * @param OptionCategory $category
335
     * @param Form           $form
336
     *
337
     * @return string[]
338
     */
339
    private function updateOptions(OptionCategory $category, Form $form)
340
    {
341
        $categories = $category->getCategories();
342
        $superCategoryName = $category->getName();
343
        $roles = [];
344
        foreach ($categories as $category) {
345
            $categoryName = $category->getName();
346
            $options = $category->getOptions();
347
348
            foreach ($options as $option) {
349
                $optionName = $option->getName();
350
                $optionType = $option->getType();
351
                $fieldName = $superCategoryName . '_' .
352
                    str_replace('.', '_', $categoryName) .
353
                    '_' . $optionName;
354
                if (!$form->has($fieldName)) {
355
                    // should be the case only for checkbox
356
                    $fieldValue = false;
357
                } else {
358
                    $fieldValue = $form->get($fieldName);
359
                }
360
                settype($fieldValue, $optionType);
361
                if ($optionType == 'boolean' && $fieldValue) {
362
                    $roles[] = 'ROLE_' .
363
                        strtoupper($superCategoryName) . '_' .
364
                        strtoupper($categoryName) . '_' .
365
                        strtoupper($optionName);
366
                }
367
                $option->setValue($fieldValue);
368
            }
369
        }
370
371
        return $roles;
372
    }
373
}
374