Passed
Push — master ( 700b0f...aafb0a )
by Björn
18:25 queued 10s
created

UsersController   A

Complexity

Total Complexity 41

Size/Duplication

Total Lines 368
Duplicated Lines 32.88 %

Coupling/Cohesion

Components 1
Dependencies 10

Test Coverage

Coverage 26.98%

Importance

Changes 0
Metric Value
wmc 41
lcom 1
cbo 10
dl 121
loc 368
ccs 51
cts 189
cp 0.2698
rs 9.1199
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A onDispatch() 0 27 1
A indexAction() 0 32 2
B addAction() 40 40 5
B editAction() 49 49 7
B deleteAction() 0 40 6
B confirmAction() 12 54 9
B activateAction() 12 49 7
A getUserTable() 0 8 2
A getAclroleTable() 8 8 2

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like UsersController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use UsersController, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * BB's Zend Framework 2 Components
4
 *
5
 * AdminModule
6
 *
7
 * @package   [MyApplication]
8
 * @package   BB's Zend Framework 2 Components
9
 * @package   AdminModule
10
 * @author    Björn Bartels <[email protected]>
11
 * @link      https://gitlab.bjoernbartels.earth/groups/zf2
12
 * @license   http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
13
 * @copyright copyright (c) 2016 Björn Bartels <[email protected]>
14
 */
15
16
namespace Admin\Controller;
17
18
use Application\Controller\BaseActionController;
19
use Zend\View\Model\ViewModel;
20
use Admin\Module as AdminModule;
21
use Admin\Model\User;
22
use Admin\Form\UserForm;
23
use Admin;
24
use Admin\Model\AclroleTable;
25
26
class UsersController extends BaseActionController
27
{
28
29
	/**
30
	 * @var array|\Admin\Model\UserTable
31
	 */
32
	protected $userTable;
33
34
	/**
35
	 * @var array|\Admin\Model\AclroleTable
36
	 */
37
	protected $AclroleTable;
38
39
    /**
40
     * initialize titles and toolbar items
41
     *
42
     * {@inheritDoc}
43
     * @see \Zend\Mvc\Controller\AbstractActionController::onDispatch()
44
     */
45
    public function onDispatch(\Zend\Mvc\MvcEvent $e)
46
    {
47
        $this->setToolbarItems(
48
            array(
49
            "index" => array(
50
            array(
51
            'label'            => 'add user',
52
            'icon'            => 'plus',
53
            'class'            => 'button btn btn-default small btn-sm btn-cta-xhr cta-xhr-modal',
54
            'route'            => 'admin/default',
55
            'controller'    => 'users',
56
            'action'        => 'add',
57
            'resource'        => 'mvc:user',
58
            ),
59
            ),
60
            )
61
        );
62
        $this->setActionTitles(
63
            array(
64
            'index' => $this->translate("manage users"),
65
            'add' => $this->translate("add user"),
66
            'edit' => $this->translate("edit user"),
67
            'delete' => $this->translate("delete user"),
68
            )
69
        );
70
        return parent::onDispatch($e);
71
    }
72
73
    /**
74
     * list users in a table
75
     * @return mixed|\Zend\Http\Response|\Zend\View\Model\ViewModel
76
     */
77 1
    public function indexAction()
78
    {
79 1
        $tmplVars = $this->getTemplateVars();
0 ignored issues
show
Unused Code introduced by
$tmplVars is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
80 1
        $aUserlist = $this->getUserTable()->fetchAll();
81 1
        if ( $this->isXHR() ) {
82
            $datatablesData = array('data' => $aUserlist->toArray());
83
            $oController = $this;
84
            $datatablesData['data'] = array_map(
85
                function ($row) use ($oController) {
86
                    $actions = '<div class="button-group tiny btn-group btn-group-xs">'.
87
                    '<a class="button btn btn-default tiny btn-xs btn-clean btn-cta-xhr cta-xhr-modal" href="'.$oController->url()->fromRoute(
88
                        'admin/default',
89
                        array('controller'=>'users', 'action'=>'edit', 'user_id' => $row["user_id"])
90
                    ).'"><span class="fa fa-pencil"></span> '.$oController->translate("edit").'</a>'.
91
                    '<a class="button btn btn-default tiny btn-xs btn-clean btn-cta-xhr cta-xhr-modal" href="'.$oController->url()->fromRoute(
92
                        'admin/default',
93
                        array('controller'=>'users', 'action'=>'delete', 'user_id' => $row["user_id"])
94
                    ).'"><span class="fa fa-trash-o"></span> '.$oController->translate("delete").'</a>'.
95
                    '</div>';
96
                    $row["password"] = "*********";
97
                    $row["_actions_"] = $actions;
98
                    return $row;
99
                }, $datatablesData['data']
100
            );
101
            return $this->getResponse()->setContent(json_encode($datatablesData));
102
        }
103 1
        return new ViewModel(
104
            array(
105 1
                'userdata' => $aUserlist,
106
            )
107
        );
108
    }
109
110
    /**
111
     * add user entry
112
     * @return mixed|\Zend\Http\Response|\Zend\View\Model\ViewModel
113
     */
114 1 View Code Duplication
    public function addAction()
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...
115
    {
116 1
        $tmplVars = $this->getTemplateVars(
117
            array(
118 1
                'showForm'    => true,
119
            )
120
        );
121 1
        $form = new UserForm();
122
123 1
        $roles = $this->getAclroleTable()->fetchAll()->toArray();
124 1
        $valueoptions = array();
125 1
        foreach ($roles as $role) {
126 1
            $valueoptions[$role["roleslug"]] = $role["rolename"];
127
        }
128
        /** @var \Zend\Form\Element\Select $aclroleSelect */
129 1
        $aclroleSelect = $form->get('aclrole');
130 1
        $aclroleSelect->setValueOptions($valueoptions);
131
132 1
        $request = $this->getRequest();
133 1
        $user = new User();
134 1
        if ($request->isPost()) {
135
            $form->setInputFilter($user->getInputFilter());
136
            $form->setData($request->getPost());
137
138
            if ($form->isValid()) {
139
                $user->exchangeArray($form->getData());
140
                $this->getUserTable()->saveUser($user);
141
                $this->flashMessenger()->addSuccessMessage($this->translate("user has been saved"));
142
                if ( $this->isXHR() ) {
143
                    $tmplVars["showForm"] = false;
144
                } else {
145
                    return $this->redirect()->toRoute('admin/default', array('controller' => 'users'));
146
                }
147
148
            }
149
            $tmplVars["user"] = $user;
150
        }
151 1
        $tmplVars["form"] = $form;
152 1
        return new ViewModel($tmplVars);
153
    }
154
155
    /**
156
     * edit user entry
157
     * @return mixed|\Zend\Http\Response|\Zend\View\Model\ViewModel
158
     */
159 1 View Code Duplication
    public function editAction()
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...
160
    {
161 1
        $tmplVars = $this->getTemplateVars(
162
            array(
163 1
                'showForm'    => true,
164
            )
165
        );
166 1
        $id = (int) $this->params()->fromRoute('user_id', 0);
167 1
        if (!$id) {
168
            $this->flashMessenger()->addWarningMessage($this->translate("missing parameters"));
169
            return $this->redirect()->toRoute('admin/default', array('controller' => 'users'));
170
        }
171
        try {
172 1
            $user = $this->getUserTable()->getUser($id);
173
        } catch (\Exception $e) {
174
            $this->flashMessenger()->addWarningMessage($this->translate("invalid parameters"));
175
            return $this->redirect()->toRoute('admin/default', array('controller' => 'users'));
176
        }
177
178 1
        $form    = new UserForm();
179 1
        $form->bind($user);
180
181 1
        $roles = $this->getAclroleTable()->fetchAll()->toArray();
182 1
        $valueoptions = array();
183 1
        foreach ($roles as $role) {
184 1
            $valueoptions[$role["roleslug"]] = $role["rolename"];
185
        }
186 1
        $form->get('aclrole')->setValueOptions($valueoptions);
0 ignored issues
show
Bug introduced by
The method setValueOptions() does not exist on Zend\Form\ElementInterface. Did you maybe mean setValue()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
187
188 1
        $request = $this->getRequest();
189 1
        if ($request->isPost()) {
190
            $form->setInputFilter($user->getInputFilter());
191
            $form->setData($request->getPost());
192
            if ($form->isValid()) {
193
                $this->getUserTable()->saveUser($user);
194
                $this->flashMessenger()->addSuccessMessage($this->translate("user has been saved"));
195
                if ( $this->isXHR() ) {
196
                    $tmplVars["showForm"] = false;
197
                } else {
198
                    return $this->redirect()->toRoute('admin/default', array('controller' => 'users'));
199
                }
200
            }
201
        } else {
202 1
            $form->bind($user);
203
        }
204 1
        $tmplVars["user_id"] = $id;
205 1
        $tmplVars["form"] = $form;
206 1
        return new ViewModel($tmplVars);
207
    }
208
209
    /**
210
     * delete user entry
211
     * @return mixed|\Zend\Http\Response|\Zend\View\Model\ViewModel
212
     */
213 1
    public function deleteAction()
214
    {
215 1
        $tmplVars = $this->getTemplateVars(
216
            array(
217 1
                'showForm'    => true,
218
            )
219
        );
220 1
        $id = (int) $this->params()->fromRoute('user_id', 0);
221 1
        if (!$id) {
222
            $this->flashMessenger()->addWarningMessage($this->translate("missing parameters"));
223
            return $this->redirect()->toRoute('admin/default', array('controller' => 'users'));
224
        }
225
226 1
        $tmplVars["user_id"] = $id;
227
        try {
228 1
            $user = $this->getUserTable()->getUser($id);
229
        } catch (\Exception $e) {
230
            $this->flashMessenger()->addWarningMessage($this->translate("invalid parameters"));
231
            return $this->redirect()->toRoute('admin/default', array('controller' => 'users'));
232
        }
233 1
        $tmplVars["user"] = $user;
234
235 1
        $request = $this->getRequest();
236 1
        if ($request->isPost()) {
237
            $del = $request->getPost('del', '');
238
239
            if (!empty($del)) {
240
                $id = (int) $request->getPost('id');
241
                $this->getUserTable()->deleteUser($id);
242
                $this->flashMessenger()->addSuccessMessage($this->translate("user has been deleted"));
243
                if ( $this->isXHR() ) {
244
                    $tmplVars["showForm"] = false;
245
                } else {
246
                    return $this->redirect()->toRoute('admin/default', array('controller' => 'users'));
247
                }
248
            }
249
250
        }
251 1
        return new ViewModel($tmplVars);
252
    }
253
254
    /**
255
     * confirm user registration
256
     * @return mixed|\Zend\Http\Response|\Zend\View\Model\ViewModel
257
     */
258
    public function confirmAction()
259
    {
260
        $tmplVars = array_merge(
0 ignored issues
show
Unused Code introduced by
$tmplVars is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
261
            $this->params()->fromRoute(),
262
            $this->params()->fromPost(),
263
            array()
264
        );
265
        $config = $this->getServiceLocator()->get('Config');
266
        $users = $this->getServiceLocator()->get('zfcuser_user_mapper');
267
268
        $user_id    = $this->params()->fromRoute('user_id', '');
269
        $token        = $this->params()->fromRoute('confirmtoken', '');
270 View Code Duplication
        if (empty($user_id) || empty($token)) {
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...
271
            $this->flashMessenger()->addWarningMessage($this->translate("missing parameters"));
272
            return $this->redirect()->toRoute($config["zfcuser_registration_redirect_route"], array());
273
        }
274
275
        if (is_numeric($user_id) ) {
276
            $oUser = $users->findById($user_id);
277
        } else {
278
            $oUser = $users->findByUsername($user_id);
279
        }
280 View Code Duplication
        if (!$oUser ) {
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...
281
            $this->flashMessenger()->addWarningMessage($this->translate("user could not be found"));
282
            return $this->redirect()->toRoute($config["zfcuser_registration_redirect_route"], array());
283
        }
284 View Code Duplication
        if (($oUser->getState() != 0) || ($oUser->getToken() != $token) ) {
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...
285
            $this->flashMessenger()->addWarningMessage($this->translate("confirmation token is invalid"));
286
            return $this->redirect()->toRoute($config["zfcuser_registration_redirect_route"], array());
287
        }
288
289
        // all ok, do stuff...
290
        $oModule = new AdminModule();
291
        $oModule->setAppConfig($config);
292
        $this->getUserTable()->getTableGateway()->update(
293
            array(
294
            "state"        => ($config["zfcuser_admin_must_activate"]) ? "0" : "1",
295
            "token"        => $oModule->createUserToken($oUser),
296
            ), array(
297
            "user_id"    => $oUser->getId(),
298
            )
299
        );
300
        $oUser = $users->findById($user_id);
301
        $this->flashMessenger()->addSuccessMessage($this->translate("user's registration has been confirmed"));
302
        if ($config["zfcuser_admin_must_activate"]) {
303
            $oModule->sendActivationMail($oUser);
304
            $this->flashMessenger()->addInfoMessage($this->translate("admin has been notified for activation"));
305
            return $this->redirect()->toRoute($config["zfcuser_registration_redirect_route"], array());
306
        } else {
307
            $this->flashMessenger()->addSuccessMessage($this->translate("user has been activated"));
308
            return $this->redirect()->toRoute('zfcuser/login', array());
309
        }
310
311
    }
312
313
    /**
314
     * active user registration
315
     * @return mixed|\Zend\Http\Response|\Zend\View\Model\ViewModel
316
     */
317
    public function activateAction()
318
    {
319
        $tmplVars = array_merge(
0 ignored issues
show
Unused Code introduced by
$tmplVars is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
320
            $this->params()->fromRoute(),
321
            $this->params()->fromPost(),
322
            array()
323
        );
324
        $config    = $this->getServiceLocator()->get('Config');
325
        $users    = $this->getServiceLocator()->get('zfcuser_user_mapper');
326
327
        $user_id    = $this->params()->fromRoute('user_id', '');
328
        $token        = $this->params()->fromRoute('activatetoken', '');
329 View Code Duplication
        if (empty($user_id) || empty($token)) {
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...
330
            $this->flashMessenger()->addWarningMessage($this->translate("missing parameters"));
331
            return $this->redirect()->toRoute($config["zfcuser_registration_redirect_route"], array());
332
        }
333
334
        if (is_numeric($user_id) ) {
335
            $oUser = $users->findById($user_id);
336
        } else {
337
            $oUser = $users->findByUsername($user_id);
338
        }
339 View Code Duplication
        if (!$oUser ) {
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...
340
            $this->flashMessenger()->addWarningMessage($this->translate("user could not be found"));
341
            return $this->redirect()->toRoute($config["zfcuser_registration_redirect_route"], array());
342
        }
343 View Code Duplication
        if (($oUser->getState() != 0) || ($oUser->getToken() != $token) ) {
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...
344
            $this->flashMessenger()->addWarningMessage($this->translate("activation token is invalid"));
345
            return $this->redirect()->toRoute($config["zfcuser_registration_redirect_route"], array());
346
        }
347
348
        // all ok, do stuff...
349
        $oModule = new AdminModule();
350
        $oModule->setAppConfig($config);
351
        $this->getUserTable()->getTableGateway()->update(
352
            array(
353
                "state"        => "1",
354
                "token"        => "",
355
            ), array(
356
                "user_id"    => $oUser->getId(),
357
            )
358
        );
359
        $oUser = $users->findById($user_id);
360
        $this->flashMessenger()->addSuccessMessage($this->translate("user has been activated"));
361
        $oModule->sendActivationNotificationMail($oUser);
362
363
        return $this->redirect()->toRoute($config["zfcuser_registration_redirect_route"], array());
364
365
    }
366
367
    /**
368
     * retrieve user data table
369
     * @return array|\Admin\Model\UserTable
370
     */
371
    public function getUserTable()
372
    {
373
        if (!$this->userTable) {
374
            $sm = $this->getServiceLocator();
375
            $this->userTable = $sm->get('AdminUserTable');
376
        }
377
        return $this->userTable;
378
    }
379
380
    /**
381
     * retrieve role item table
382
     * @return array|\Admin\Model\AclroleTable
383
     */
384 View Code Duplication
    public function getAclroleTable()
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...
385
    {
386
        if (!$this->AclroleTable) {
387
            $sm = $this->getServiceLocator();
388
            $this->AclroleTable = $sm->get('AdminAclroleTable');
389
        }
390
        return $this->AclroleTable;
391
    }
392
393
}
394