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