Passed
Pull Request — master (#58)
by Stone
04:29 queued 02:04
created

Home::updateUser()   F

Complexity

Conditions 17
Paths 1280

Size

Total Lines 80
Code Lines 50

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 17
eloc 50
nc 1280
nop 0
dl 0
loc 80
rs 1.0499
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace App\Controllers\Admin;
4
5
6
use App\Models\RoleModel;
7
use App\Models\UserModel;
8
use Core\Constant;
9
use Core\Container;
10
use Core\Traits\PasswordFunctions;
11
use Core\Traits\StringFunctions;
12
13
class Home extends \Core\AdminController
14
{
15
    use StringFunctions;
0 ignored issues
show
Bug introduced by
The trait Core\Traits\StringFunctions requires the property $childNodes which is not provided by App\Controllers\Admin\Home.
Loading history...
16
    use PasswordFunctions;
17
    protected $siteConfig;
18
    protected $pagination;
19
20
    private $userModel;
21
    private $roleModel;
22
23
    public function __construct(Container $container)
24
    {
25
        $this->loadModules[] = 'SiteConfig';
26
        $this->loadModules[] = 'pagination';
27
        parent::__construct($container);
28
        $this->userModel = new UserModel($this->container);
29
        $this->roleModel = new RoleModel($this->container);
30
31
        $this->data['configs'] = $this->siteConfig->getSiteConfig();
32
    }
33
34
    /**
35
     * The front page of the admin section. We display the user info
36
     * @throws \ReflectionException
37
     * @throws \Twig_Error_Loader
38
     * @throws \Twig_Error_Runtime
39
     * @throws \Twig_Error_Syntax
40
     */
41
    public function index()
42
    {
43
        $this->onlyUser();
44
45
        //check if have prefilled form data and error mesages
46
        $this->data["registrationInfo"] = $this->session->get("registrationInfo");
47
        $this->data["registrationErrors"] = $this->session->get("registrationErrors");
48
49
        //remove the set data as it is now sent to the template
50
        $this->session->remove("registrationInfo");
51
        $this->session->remove("registrationErrors");
52
53
        $userId = $this->session->get("userId");
54
        $this->data["user"] = $this->userModel->getUserDetailsById($userId);
0 ignored issues
show
Bug introduced by
It seems like $userId can also be of type null; however, parameter $userId of App\Models\UserModel::getUserDetailsById() does only seem to accept integer, 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

54
        $this->data["user"] = $this->userModel->getUserDetailsById(/** @scrutinizer ignore-type */ $userId);
Loading history...
55
56
        $this->data["roles"] = $this->roleModel->getRoleList();
57
58
        $this->renderView('Admin/Home');
59
    }
60
61
    /**
62
     * Administrate a user as an admin
63
     * @param int $userId
64
     * @throws \ReflectionException
65
     * @throws \Twig_Error_Loader
66
     * @throws \Twig_Error_Runtime
67
     * @throws \Twig_Error_Syntax
68
     */
69
    public function viewUser(int $userId)
70
    {
71
        $this->onlyAdmin();
72
        if (!$this->isInt($userId)) {
73
            throw new \Exception("Error in passed ID");
74
        }
75
76
        //check if have prefilled form data and error mesages
77
        $this->data["registrationInfo"] = $this->session->get("registrationInfo");
78
        $this->data["registrationErrors"] = $this->session->get("registrationErrors");
79
80
        //remove the set data as it is now sent to the template
81
        $this->session->remove("registrationInfo");
82
        $this->session->remove("registrationErrors");
83
84
        $this->data["user"] = $this->userModel->getUserDetailsById($userId);
85
86
        $this->data["roles"] = $this->roleModel->getRoleList();
87
88
        $this->renderView('Admin/Home');
89
    }
90
91
    /**
92
     * Update the user info via post
93
     * @throws \Exception
94
     */
95
    public function updateUser()
96
    {
97
        $this->onlyUser();
98
        $this->onlyPost();
99
100
        $user = (object)$this->request->getDataFull();
101
        $redirectUrl = "/admin";
102
103
        if ($user->userId !== $this->session->get("userId") || isset($user->userRoleSelector) || isset($user->locked_out)) {
104
            //an admin is trying to update a user or form tampered with
105
            $this->onlyAdmin();
106
            $redirectUrl = "/admin/home/view-user/" . $user->userId;
107
        } else {
108
            //set the role to the original state for update
109
            $beforeUser = $this->userModel->getUserDetailsById($user->userId);
110
            $user->userRoleSelector = $beforeUser->roles_idroles;
111
            $user->userLockedOut = $beforeUser->locked_out;
112
        }
113
114
        $userId = $user->userId;
115
        $password = $user->forgotPassword ?? "";
116
        $confirm = $user->forgotConfirm ?? "";
117
        $resetPassword = false;
118
        $error = false;
119
        $registerErrors = new \stdClass();
120
121
        if($userId == 1 && $user->userLockedOut == 1)
122
        {
123
            $error = true;
124
            $this->alertBox->setAlert("Original admin may not be deactivated", "error");
125
        }
126
127
        if($userId == 1 && $user->userRoleSelector != 2)
128
        {
129
            $error = true;
130
            $this->alertBox->setAlert("Original admin must stay admin", "error");
131
        }
132
133
        if ($password !== "" || $confirm !== "") {
134
            //we are resetting the password
135
            $resetPassword = true;
136
            if ($password !== $confirm) {
137
                $error = true;
138
                $registerErrors->forgotPassword = "password and confirmation do not match";
139
                $registerErrors->forgotConfirm = "password and confirmation do not match";
140
            }
141
142
            $passwordError = $this->isPasswordComplex($password);
143
            if (!$passwordError["success"]) {
144
                $error = true;
145
                $registerErrors->forgotPassword = $passwordError["message"];
146
            }
147
        }
148
149
        if ($user->userName == "") {
150
            $error = true;
151
            $registerErrors->userName = "name must not be empty";
152
        }
153
        if ($user->userSurname == "") {
154
            $error = true;
155
            $registerErrors->userSurname = "surname must not be empty";
156
        }
157
        if ($user->userUsername == "") {
158
            $error = true;
159
            $registerErrors->userUsername = "username must not be empty";
160
        }
161
162
        if ($error) {
163
            $this->session->set("registrationErrors", $registerErrors);
164
            $this->response->redirect($redirectUrl);
165
        }
166
167
        if ($resetPassword) {
168
            $this->userModel->resetPassword($userId, $password);
169
        }
170
171
        $this->userModel->updateUser($user);
172
173
        $this->alertBox->setAlert('User details updated');
174
        $this->response->redirect($redirectUrl);
175
    }
176
177
    /**
178
     * List all the users
179
     * @param string $page
180
     * @param int $linesPerPage
181
     * @throws \ReflectionException
182
     * @throws \Twig_Error_Loader
183
     * @throws \Twig_Error_Runtime
184
     * @throws \Twig_Error_Syntax
185
     */
186
    public function listUsers(string $page = "page-1", int $linesPerPage = Constant::LIST_PER_PAGE)
187
    {
188
        $this->onlyAdmin();
189
190
        $totalUsers = $this->userModel->countUsers();
191
        $pagination = $this->pagination->getPagination($page, $totalUsers, $linesPerPage);
192
193
        if ($linesPerPage !== Constant::LIST_PER_PAGE) {
194
            $this->data['paginationPostsPerPage'] = $linesPerPage;
195
        }
196
197
        $this->data["posts"] = $this->userModel->getUserList($pagination["offset"], $linesPerPage);
198
        $this->data['pagination'] = $pagination;
199
        $this->renderView("Admin/ListUser");
200
    }
201
202
    /**
203
     * permanantly delete a user
204
     * @param int $userId
205
     * @throws \Exception
206
     */
207
    public function deleteUser(int $userId)
208
    {
209
        $this->onlyAdmin();
210
        if (!$this->isInt($userId)) {
211
            throw new \Exception("Error in passed ID");
212
        }
213
214
        if($userId === 1)
215
        {
216
            $this->alertBox->setAlert('Original Admin can not be deleted', "error");
217
            $this->response->redirect("/admin/home/list-users");
218
        }
219
220
        $this->userModel->deleteUser($userId);
221
        $this->alertBox->setAlert('User deleted');
222
        $this->response->redirect("/admin/home/list-users");
223
    }
224
}