Passed
Push — master ( f4ed7b...a5499f )
by Darko
11:21
created

AdminUserController   C

Complexity

Total Complexity 54

Size/Duplication

Total Lines 283
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 54
eloc 184
dl 0
loc 283
rs 6.4799
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A verify() 0 10 2
F index() 0 81 19
F edit() 0 145 28
A destroy() 0 17 3
A resendVerification() 0 12 2

How to fix   Complexity   

Complex Class

Complex classes like AdminUserController 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 AdminUserController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace App\Http\Controllers\Admin;
4
5
use App\Http\Controllers\BasePageController;
6
use App\Models\Invitation;
7
use App\Models\User;
8
use Illuminate\Http\RedirectResponse;
9
use Illuminate\Http\Request;
10
use Jrean\UserVerification\Facades\UserVerification;
11
use Spatie\Permission\Models\Role;
12
use Stevebauman\Location\Facades\Location;
13
14
class AdminUserController extends BasePageController
15
{
16
    /**
17
     * @throws \Throwable
18
     */
19
    public function index(Request $request)
20
    {
21
        $this->setAdminPrefs();
22
23
        $meta_title = $title = 'User List';
24
25
        $roles = [];
26
        $userRoles = Role::cursor()->remember();
27
        foreach ($userRoles as $userRole) {
28
            $roles[$userRole->id] = $userRole->name;
29
        }
30
31
        $ordering = getUserBrowseOrdering();
32
        $orderBy = $request->has('ob') && \in_array($request->input('ob'), $ordering, false) ? $request->input('ob') : '';
33
        $page = $request->has('page') && is_numeric($request->input('page')) ? $request->input('page') : 1;
34
        $offset = ($page - 1) * config('nntmux.items_per_page');
35
36
        $variables = [
37
            'username' => $request->has('username') ? $request->input('username') : '',
38
            'email' => $request->has('email') ? $request->input('email') : '',
39
            'host' => $request->has('host') ? $request->input('host') : '',
40
            'role' => $request->has('role') ? $request->input('role') : '',
41
            'created_from' => $request->has('created_from') ? $request->input('created_from') : '',
42
            'created_to' => $request->has('created_to') ? $request->input('created_to') : '',
43
        ];
44
45
        $result = User::getRange(
46
            $offset,
47
            config('nntmux.items_per_page'),
48
            $orderBy,
49
            $variables['username'],
50
            $variables['email'],
51
            $variables['host'],
52
            $variables['role'],
53
            true,
54
            $variables['created_from'],
55
            $variables['created_to']
56
        );
57
58
        $results = $this->paginate($result ?? [], User::getCount($variables['role'], $variables['username'], $variables['host'], $variables['email'], $variables['created_from'], $variables['created_to']) ?? 0, config('nntmux.items_per_page'), $page, $request->url(), $request->query());
59
60
        // Add country data to each user based on their host IP
61
        foreach ($results as $user) {
62
            $position = null;
63
            if (! empty($user->host) && filter_var($user->host, FILTER_VALIDATE_IP)) {
64
                $position = Location::get($user->host);
65
            }
66
            $user->country_name = $position ? $position->countryName : null;
67
            $user->country_code = $position ? $position->countryCode : null;
68
69
            // Add daily API and download counts
70
            try {
71
                $user->daily_api_count = \App\Models\UserRequest::getApiRequests($user->id);
72
                $user->daily_download_count = \App\Models\UserDownload::getDownloadRequests($user->id);
73
            } catch (\Exception $e) {
74
                $user->daily_api_count = 0;
75
                $user->daily_download_count = 0;
76
            }
77
        }
78
79
        // Build order by URLs
80
        $orderByUrls = [];
81
        foreach ($ordering as $orderType) {
82
            $orderByUrls['orderby'.$orderType] = url('admin/user-list?ob='.$orderType);
83
        }
84
85
        $this->viewData = array_merge($this->viewData, [
86
            'username' => $variables['username'],
87
            'email' => $variables['email'],
88
            'host' => $variables['host'],
89
            'role' => $variables['role'],
90
            'created_from' => $variables['created_from'],
91
            'created_to' => $variables['created_to'],
92
            'role_ids' => array_keys($roles),
93
            'role_names' => $roles,
94
            'userlist' => $results,
95
            'title' => $title,
96
            'meta_title' => $meta_title,
97
        ], $orderByUrls);
98
99
        return view('admin.users.index', $this->viewData);
100
    }
101
102
    /**
103
     * @return RedirectResponse|\Illuminate\View\View
104
     *
105
     * @throws \Exception
106
     */
107
    public function edit(Request $request)
108
    {
109
        $this->setAdminPrefs();
110
111
        $user = [
112
            'id' => '',
113
            'username' => '',
114
            'email' => '',
115
            'password' => '',
116
            'role' => User::ROLE_USER,
117
            'notes' => '',
118
            'rate_limit' => 60,
119
        ];
120
121
        $meta_title = $title = 'View User';
122
123
        // set the current action
124
        $action = $request->input('action') ?? 'view';
125
126
        // get the user roles
127
        $userRoles = Role::cursor()->remember();
128
        $roles = [];
129
        $defaultRole = 'User';
130
        $defaultInvites = Invitation::DEFAULT_INVITES;
131
        foreach ($userRoles as $r) {
132
            $roles[$r->id] = $r->name;
133
            if ($r->isdefault === 1) {
134
                $defaultRole = $r->id;
135
                $defaultInvites = $r->defaultinvites;
136
            }
137
        }
138
139
        $error = null;
140
141
        switch ($action) {
142
            case 'add':
143
                $user += [
144
                    'role' => $defaultRole,
145
                    'notes' => '',
146
                    'invites' => $defaultInvites,
147
                    'movieview' => 0,
148
                    'xxxview' => 0,
149
                    'musicview' => 0,
150
                    'consoleview' => 0,
151
                    'gameview' => 0,
152
                    'bookview' => 0,
153
                ];
154
                break;
155
            case 'submit':
156
                if (empty($request->input('id'))) {
157
                    $invites = $defaultInvites;
158
                    foreach ($userRoles as $role) {
159
                        if ($role['id'] === $request->input('role')) {
160
                            $invites = $role['defaultinvites'];
161
                        }
162
                    }
163
                    $ret = User::signUp($request->input('username'), $request->input('password'), $request->input('email'), '', $request->input('notes'), $invites, '', true, $request->input('role'), false);
164
                } else {
165
                    $editedUser = User::find($request->input('id'));
166
                    // Use the current grabs value since it's read-only
167
                    $ret = User::updateUser($editedUser->id, $request->input('username'), $request->input('email'), $editedUser->grabs, $request->input('role'), $request->input('notes'), $request->input('invites'), ($request->has('movieview') ? 1 : 0), ($request->has('musicview') ? 1 : 0), ($request->has('gameview') ? 1 : 0), ($request->has('xxxview') ? 1 : 0), ($request->has('consoleview') ? 1 : 0), ($request->has('bookview') ? 1 : 0));
168
                    if ($request->input('password') !== null) {
169
                        User::updatePassword($editedUser->id, $request->input('password'));
170
                    }
171
                    // Handle rolechangedate - update if has value, clear if empty
172
                    if ($request->has('rolechangedate')) {
173
                        $roleChangeDate = $request->input('rolechangedate');
174
                        if (! empty($roleChangeDate)) {
175
                            User::updateUserRoleChangeDate($editedUser->id, $roleChangeDate);
176
                        } else {
177
                            // Clear the rolechangedate if empty string is provided
178
                            $editedUser->update(['rolechangedate' => null]);
179
                        }
180
                    }
181
                    if ($request->input('role') !== null) {
182
                        $editedUser->refresh();
183
                    }
184
                }
185
186
                if ($ret >= 0) {
187
                    return redirect()->to('admin/user-list');
188
                }
189
190
                switch ($ret) {
191
                    case User::ERR_SIGNUP_BADUNAME:
192
                        $error = 'Bad username. Try a better one.';
193
                        break;
194
                    case User::ERR_SIGNUP_BADPASS:
195
                        $error = 'Bad password. Try a longer one.';
196
                        break;
197
                    case User::ERR_SIGNUP_BADEMAIL:
198
                        $error = 'Bad email.';
199
                        break;
200
                    case User::ERR_SIGNUP_UNAMEINUSE:
201
                        $error = 'Username in use.';
202
                        break;
203
                    case User::ERR_SIGNUP_EMAILINUSE:
204
                        $error = 'Email in use.';
205
                        break;
206
                    default:
207
                        $error = 'Unknown save error.';
208
                        break;
209
                }
210
                $user += [
211
                    'id' => $request->input('id'),
212
                    'username' => $request->input('username'),
213
                    'email' => $request->input('email'),
214
                    'role' => $request->input('role'),
215
                    'notes' => $request->input('notes'),
216
                ];
217
                break;
218
            case 'view':
219
            default:
220
                if ($request->has('id')) {
221
                    $title = 'User Edit';
222
                    $id = $request->input('id');
223
                    $user = User::find($id);
224
225
                    // Add daily API and download counts
226
                    if ($user) {
227
                        try {
228
                            $user->daily_api_count = \App\Models\UserRequest::getApiRequests($user->id);
229
                            $user->daily_download_count = \App\Models\UserDownload::getDownloadRequests($user->id);
230
                        } catch (\Exception $e) {
231
                            $user->daily_api_count = 0;
232
                            $user->daily_download_count = 0;
233
                        }
234
                    }
235
                }
236
237
                break;
238
        }
239
240
        $this->viewData = array_merge($this->viewData, [
241
            'yesno_ids' => [1, 0],
242
            'yesno_names' => ['Yes', 'No'],
243
            'role_ids' => array_keys($roles),
244
            'role_names' => $roles,
245
            'user' => $user,
246
            'error' => $error,
247
            'title' => $title,
248
            'meta_title' => $meta_title,
249
        ]);
250
251
        return view('admin.users.edit', $this->viewData);
252
    }
253
254
    public function destroy(Request $request): RedirectResponse
255
    {
256
        if ($request->has('id')) {
257
            $user = User::find($request->input('id'));
258
            $username = $user->username; // Store username before deletion
259
260
            $user->delete();
261
262
            // Redirect with username to display in notification
263
            return redirect()->to('admin/user-list?deleted=1&username='.urlencode($username));
264
        }
265
266
        if ($request->has('redir')) {
267
            return redirect()->to($request->input('redir'));
268
        }
269
270
        return redirect()->to($request->server('HTTP_REFERER'));
0 ignored issues
show
Bug introduced by
It seems like $request->server('HTTP_REFERER') can also be of type array; however, parameter $path of Illuminate\Routing\Redirector::to() does only seem to accept string, 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

270
        return redirect()->to(/** @scrutinizer ignore-type */ $request->server('HTTP_REFERER'));
Loading history...
271
    }
272
273
    public function resendVerification(Request $request): RedirectResponse
274
    {
275
        if ($request->has('id')) {
276
            $user = User::find($request->input('id'));
277
            UserVerification::generate($user);
278
279
            UserVerification::send($user, 'User email verification required');
280
281
            return redirect()->back()->with('success', 'Email verification for '.$user->username.' sent');
282
        }
283
284
        return redirect()->back()->with('error', 'User is invalid');
285
    }
286
287
    public function verify(Request $request): RedirectResponse
288
    {
289
        if ($request->has('id')) {
290
            $user = User::find($request->input('id'));
291
            User::query()->where('id', $request->input('id'))->update(['verified' => 1, 'email_verified_at' => now()]);
292
293
            return redirect()->back()->with('success', 'Email verification for '.$user->username.' sent');
294
        }
295
296
        return redirect()->back()->with('error', 'User is invalid');
297
    }
298
}
299