Completed
Push — dev ( db3ae6...da32ef )
by Darko
14:43 queued 10s
created

UserController   B

Complexity

Total Complexity 46

Size/Duplication

Total Lines 258
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 46
eloc 159
dl 0
loc 258
rs 8.72
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A destroy() 0 15 3
A resendVerification() 0 11 2
F edit() 0 134 28
F index() 0 57 11
A verify() 0 9 2

How to fix   Complexity   

Complex Class

Complex classes like UserController 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 UserController, 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\Jobs\SendAccountChangedEmail;
7
use App\Models\Invitation;
8
use App\Models\User;
9
use Illuminate\Http\Request;
10
use Jrean\UserVerification\Facades\UserVerification;
11
use Spatie\Permission\Models\Role;
12
13
class UserController extends BasePageController
14
{
15
    /**
16
     * @param \Illuminate\Http\Request $request
17
     *
18
     * @throws \Throwable
19
     */
20
    public function index(Request $request): void
21
    {
22
        $this->setAdminPrefs();
23
24
        $meta_title = $title = 'User List';
25
26
        $roles = [];
27
        $userRoles = Role::cursor()->remember();
28
        foreach ($userRoles as $userRole) {
29
            $roles[$userRole->id] = $userRole->name;
30
        }
31
32
        $ordering = getUserBrowseOrdering();
33
        $orderBy = $request->has('ob') && \in_array($request->input('ob'), $ordering, false) ? $request->input('ob') : '';
34
        $page = request()->has('page') && is_numeric(request()->input('page')) ? request()->input('page') : 1;
35
        $offset = ($page - 1) * config('nntmux.items_per_page');
36
37
        $variables = [
38
            'username' => $request->has('username') ? $request->input('username') : '',
39
            'email' => $request->has('email') ? $request->input('email') : '',
40
            'host' => $request->has('host') ? $request->input('host') : '',
41
            'role' => $request->has('role') ? $request->input('role') : '',
42
        ];
43
44
        $rslt = User::getRange(
45
            $offset,
46
            config('nntmux.items_per_page'),
47
            $orderBy,
48
            $variables['username'],
49
            $variables['email'],
50
            $variables['host'],
51
            $variables['role'],
52
            true
53
        );
54
55
        $results = $this->paginate($rslt ?? [], User::getCount($variables['role'], $variables['username'], $variables['host'], $variables['email']) ?? 0, config('nntmux.items_per_page'), $page, request()->url(), request()->query());
56
57
        $this->smarty->assign(
0 ignored issues
show
Bug introduced by
The method assign() does not exist on Illuminate\Foundation\Application. ( Ignorable by Annotation )

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

57
        $this->smarty->/** @scrutinizer ignore-call */ 
58
                       assign(

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...
58
            [
59
                'username'          => $variables['username'],
60
                'email'             => $variables['email'],
61
                'host'              => $variables['host'],
62
                'role'              => $variables['role'],
63
                'role_ids'          => array_keys($roles),
64
                'role_names'        => $roles,
65
                'userlist'          => $results,
66
            ]
67
        );
68
69
        foreach ($ordering as $orderType) {
70
            $this->smarty->assign('orderby'.$orderType, url('admin/user-list?ob='.$orderType));
71
        }
72
73
        $content = $this->smarty->fetch('user-list.tpl');
0 ignored issues
show
Bug introduced by
The method fetch() does not exist on Illuminate\Foundation\Application. ( Ignorable by Annotation )

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

73
        /** @scrutinizer ignore-call */ 
74
        $content = $this->smarty->fetch('user-list.tpl');

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...
74
        $this->smarty->assign(compact('title', 'meta_title', 'content'));
75
76
        $this->adminrender();
77
    }
78
79
    /**
80
     * @param Request $request
81
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
82
     * @throws \Exception
83
     */
84
    public function edit(Request $request)
85
    {
86
        $this->setAdminPrefs();
87
88
        $user = [
89
            'id' => '',
90
            'username' => '',
91
            'email' => '',
92
            'password' => '',
93
            'role' => User::ROLE_USER,
94
            'notes' => '',
95
            'rate_limit' => 60,
96
        ];
97
98
        $meta_title = $title = 'View User';
99
100
        // set the current action
101
        $action = $request->input('action') ?? 'view';
102
103
        //get the user roles
104
        $userRoles = Role::cursor()->remember();
105
        $roles = [];
106
        $defaultRole = 'User';
107
        $defaultInvites = Invitation::DEFAULT_INVITES;
108
        foreach ($userRoles as $r) {
109
            $roles[$r->id] = $r->name;
110
            if ($r->isdefault === 1) {
111
                $defaultRole = $r->id;
112
                $defaultInvites = $r->defaultinvites;
113
            }
114
        }
115
116
        switch ($action) {
117
            case 'add':
118
                $user += [
119
                    'role'        => $defaultRole,
120
                    'notes'       => '',
121
                    'invites'     => $defaultInvites,
122
                    'movieview'   => 0,
123
                    'xxxview'     => 0,
124
                    'musicview'   => 0,
125
                    'consoleview' => 0,
126
                    'gameview'    => 0,
127
                    'bookview'    => 0,
128
                ];
129
                $this->smarty->assign('user', $user);
130
                break;
131
            case 'submit':
132
                if (empty($request->input('id'))) {
133
                    $invites = $defaultInvites;
134
                    foreach ($userRoles as $role) {
135
                        if ($role['id'] === $request->input('role')) {
136
                            $invites = $role['defaultinvites'];
137
                        }
138
                    }
139
                    $ret = User::signUp($request->input('username'), $request->input('password'), $request->input('email'), '', $request->input('notes'), $invites, '', true, $request->input('role'), false);
140
                    $this->smarty->assign('role', $request->input('role'));
141
                } else {
142
                    $editedUser = User::find($request->input('id'));
143
                    $ret = User::updateUser($editedUser->id, $request->input('username'), $request->input('email'), $request->input('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));
144
                    if ($request->input('password') !== null) {
145
                        User::updatePassword($editedUser->id, $request->input('password'));
146
                    }
147
                    if ($request->input('rolechangedate') !== null) {
148
                        User::updateUserRoleChangeDate($editedUser->id, $request->input('rolechangedate'));
149
                    }
150
                    if ($request->input('role') !== null) {
151
                        $roleName = Role::query()->where('id', $request->input('role'))->value('name');
152
                        if (($roleName === 'Disabled') && config('firewall.enabled') === true && ! \Firewall::isBlacklisted($editedUser->host)) {
0 ignored issues
show
Bug introduced by
The type Firewall was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
introduced by
The condition $roleName === 'Disabled' is always false.
Loading history...
153
                            \Firewall::blacklist($editedUser->host);
154
                        }
155
                        $editedUser->refresh();
156
                        SendAccountChangedEmail::dispatch($editedUser)->onQueue('emails');
157
                    }
158
                }
159
160
                if ($ret >= 0) {
161
                    return redirect('admin/user-list');
162
                }
163
164
                switch ($ret) {
165
                    case User::ERR_SIGNUP_BADUNAME:
166
                        $this->smarty->assign('error', 'Bad username. Try a better one.');
167
                        break;
168
                    case User::ERR_SIGNUP_BADPASS:
169
                        $this->smarty->assign('error', 'Bad password. Try a longer one.');
170
                        break;
171
                    case User::ERR_SIGNUP_BADEMAIL:
172
                        $this->smarty->assign('error', 'Bad email.');
173
                        break;
174
                    case User::ERR_SIGNUP_UNAMEINUSE:
175
                        $this->smarty->assign('error', 'Username in use.');
176
                        break;
177
                    case User::ERR_SIGNUP_EMAILINUSE:
178
                        $this->smarty->assign('error', 'Email in use.');
179
                        break;
180
                    default:
181
                        $this->smarty->assign('error', 'Unknown save error.');
182
                        break;
183
                }
184
                $user += [
185
                    'id'        => $request->input('id'),
186
                    'username'  => $request->input('username'),
187
                    'email'     => $request->input('email'),
188
                    'role'      => $request->input('role'),
189
                    'notes'     => $request->input('notes'),
190
                ];
191
                $this->smarty->assign('user', $user);
192
                break;
193
            case 'view':
194
            default:
195
                if ($request->has('id')) {
196
                    $title = 'User Edit';
197
                    $id = $request->input('id');
198
                    $user = User::find($id);
199
200
                    $this->smarty->assign('user', $user);
201
                }
202
203
                break;
204
        }
205
206
        $this->smarty->assign('yesno_ids', [1, 0]);
207
        $this->smarty->assign('yesno_names', ['Yes', 'No']);
208
209
        $this->smarty->assign('role_ids', array_keys($roles));
210
        $this->smarty->assign('role_names', $roles);
211
        $this->smarty->assign('user', $user);
212
213
        $content = $this->smarty->fetch('user-edit.tpl');
214
215
        $this->smarty->assign(compact('title', 'meta_title', 'content'));
216
217
        $this->adminrender();
218
    }
219
220
    /**
221
     * @param \Illuminate\Http\Request $request
222
     *
223
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
224
     * @throws \Exception
225
     */
226
    public function destroy(Request $request)
227
    {
228
        if ($request->has('id')) {
229
            $user = User::find($request->input('id'));
230
231
            $user->delete();
232
233
            return redirect('admin/user-list');
234
        }
235
236
        if ($request->has('redir')) {
237
            return redirect($request->input('redir'));
238
        }
239
240
        return redirect($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 $to of redirect() does only seem to accept null|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

240
        return redirect(/** @scrutinizer ignore-type */ $request->server('HTTP_REFERER'));
Loading history...
241
    }
242
243
    /**
244
     * @param Request $request
245
     * @return \Illuminate\Http\RedirectResponse
246
     * @throws \Jrean\UserVerification\Exceptions\ModelNotCompliantException
247
     */
248
    public function resendVerification(Request $request)
249
    {
250
        if ($request->has('id')) {
251
            $user = User::find($request->input('id'));
252
            UserVerification::generate($user);
253
254
            UserVerification::send($user, 'User email verification required');
255
256
            return redirect()->back()->with('success', 'Email verification for '.$user->username.' sent');
0 ignored issues
show
Bug Best Practice introduced by
The expression return redirect()->back(...er->username . ' sent') also could return the type Illuminate\Routing\Redirector which is incompatible with the documented return type Illuminate\Http\RedirectResponse.
Loading history...
257
        } else {
258
            return redirect()->back()->with('error', 'User is invalid');
0 ignored issues
show
Bug Best Practice introduced by
The expression return redirect()->back(...or', 'User is invalid') also could return the type Illuminate\Routing\Redirector which is incompatible with the documented return type Illuminate\Http\RedirectResponse.
Loading history...
259
        }
260
    }
261
262
    public function verify(Request $request)
263
    {
264
        if ($request->has('id')) {
265
            $user = User::find($request->input('id'));
266
            User::query()->where('id', $request->input('id'))->update(['verified' => 1, 'email_verified_at' => now()]);
267
268
            return redirect()->back()->with('success', 'Email verification for '.$user->username.' sent');
269
        } else {
270
            return redirect()->back()->with('error', 'User is invalid');
271
        }
272
    }
273
}
274