Passed
Branch ops-updates (277b44)
by Björn
05:09
created

UsersController   A

Complexity

Total Complexity 41

Size/Duplication

Total Lines 365
Duplicated Lines 0 %

Test Coverage

Coverage 26.98%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 212
c 1
b 0
f 0
dl 0
loc 365
ccs 51
cts 189
cp 0.2698
rs 9.1199
wmc 41

9 Methods

Rating   Name   Duplication   Size   Complexity  
B confirmAction() 0 51 9
B editAction() 0 48 7
B deleteAction() 0 39 6
B activateAction() 0 47 7
A addAction() 0 39 5
A onDispatch() 0 26 1
A indexAction() 0 29 2
A getAclroleTable() 0 7 2
A getUserTable() 0 7 2

How to fix   Complexity   

Complex Class

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.

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
The assignment to $tmplVars is dead and can be removed.
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
    public function addAction()
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()) {
0 ignored issues
show
Bug introduced by
The method isPost() does not exist on Zend\Stdlib\RequestInterface. It seems like you code against a sub-type of Zend\Stdlib\RequestInterface such as Zend\Http\Request. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

134
        if ($request->/** @scrutinizer ignore-call */ isPost()) {
Loading history...
135
            $form->setInputFilter($user->getInputFilter());
136
            $form->setData($request->getPost());
0 ignored issues
show
Bug introduced by
The method getPost() does not exist on Zend\Stdlib\RequestInterface. It seems like you code against a sub-type of Zend\Stdlib\RequestInterface such as Zend\Http\Request. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

136
            $form->setData($request->/** @scrutinizer ignore-call */ getPost());
Loading history...
137
138
            if ($form->isValid()) {
139
                $user->exchangeArray($form->getData());
0 ignored issues
show
Bug introduced by
It seems like $form->getData() can also be of type object; however, parameter $data of Admin\Model\User::exchangeArray() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

139
                $user->exchangeArray(/** @scrutinizer ignore-type */ $form->getData());
Loading history...
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
    public function editAction()
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\FieldsetInterface. Did you maybe mean setValue()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

186
        $form->get('aclrole')->/** @scrutinizer ignore-call */ setValueOptions($valueoptions);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Bug introduced by
The method setValueOptions() does not exist on Zend\Form\ElementInterface. Did you maybe mean setValue()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

186
        $form->get('aclrole')->/** @scrutinizer ignore-call */ setValueOptions($valueoptions);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

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
The assignment to $tmplVars is dead and can be removed.
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
        if (empty($user_id) || empty($token)) {
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
        if (!$oUser ) {
281
            $this->flashMessenger()->addWarningMessage($this->translate("user could not be found"));
282
            return $this->redirect()->toRoute($config["zfcuser_registration_redirect_route"], array());
283
        }
284
        if (($oUser->getState() != 0) || ($oUser->getToken() != $token) ) {
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
The assignment to $tmplVars is dead and can be removed.
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
        if (empty($user_id) || empty($token)) {
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
        if (!$oUser ) {
340
            $this->flashMessenger()->addWarningMessage($this->translate("user could not be found"));
341
            return $this->redirect()->toRoute($config["zfcuser_registration_redirect_route"], array());
342
        }
343
        if (($oUser->getState() != 0) || ($oUser->getToken() != $token) ) {
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
    public function getAclroleTable()
385
    {
386
        if (!$this->AclroleTable) {
387
            $sm = $this->getServiceLocator();
388
            $this->AclroleTable = $sm->get('AdminAclroleTable');
389
        }
390
        return $this->AclroleTable;
391
    }
392
393
}
394