Passed
Push — master ( 288d66...17f8a8 )
by Jeremy
03:39
created

UsersManagementController   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 271
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
dl 0
loc 271
rs 10
c 2
b 0
f 0
wmc 21

9 Methods

Rating   Name   Duplication   Size   Complexity  
A create() 0 9 1
B search() 0 35 3
A index() 0 6 1
B update() 0 57 8
A edit() 0 16 2
A store() 0 49 2
A __construct() 0 3 1
A destroy() 0 15 2
A show() 0 5 1
1
<?php
2
3
namespace App\Http\Controllers;
4
5
use App\Models\Profile;
6
use App\Models\User;
7
use App\Traits\CaptureIpTrait;
8
use Auth;
9
use Illuminate\Http\Response;
10
use Illuminate\Http\Request;
11
use jeremykenedy\LaravelRoles\Models\Role;
12
use Validator;
13
14
class UsersManagementController extends Controller
15
{
16
    /**
17
     * Create a new controller instance.
18
     *
19
     * @return void
20
     */
21
    public function __construct()
22
    {
23
        $this->middleware('auth');
24
    }
25
26
    /**
27
     * Display a listing of the resource.
28
     *
29
     * @return \Illuminate\Http\Response
30
     */
31
    public function index()
32
    {
33
        $users = User::paginate(env('USER_LIST_PAGINATION_SIZE'));
34
        $roles = Role::all();
35
36
        return View('usersmanagement.show-users', compact('users', 'roles'));
0 ignored issues
show
Bug Best Practice introduced by
The expression return View('usersmanage...pact('users', 'roles')) returns the type Illuminate\View\View which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
37
    }
38
39
    /**
40
     * Show the form for creating a new resource.
41
     *
42
     * @return \Illuminate\Http\Response
43
     */
44
    public function create()
45
    {
46
        $roles = Role::all();
47
48
        $data = [
49
            'roles' => $roles,
50
        ];
51
52
        return view('usersmanagement.create-user')->with($data);
0 ignored issues
show
Bug Best Practice introduced by
The expression return view('usersmanage...ate-user')->with($data) returns the type Illuminate\View\View which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
53
    }
54
55
    /**
56
     * Store a newly created resource in storage.
57
     *
58
     * @param \Illuminate\Http\Request $request
59
     *
60
     * @return \Illuminate\Http\Response
61
     */
62
    public function store(Request $request)
63
    {
64
        $validator = Validator::make($request->all(),
65
            [
66
                'name'                  => 'required|max:255|unique:users',
67
                'first_name'            => '',
68
                'last_name'             => '',
69
                'email'                 => 'required|email|max:255|unique:users',
70
                'password'              => 'required|min:6|max:20|confirmed',
71
                'password_confirmation' => 'required|same:password',
72
                'role'                  => 'required',
73
            ],
74
            [
75
                'name.unique'         => trans('auth.userNameTaken'),
76
                'name.required'       => trans('auth.userNameRequired'),
77
                'first_name.required' => trans('auth.fNameRequired'),
78
                'last_name.required'  => trans('auth.lNameRequired'),
79
                'email.required'      => trans('auth.emailRequired'),
80
                'email.email'         => trans('auth.emailInvalid'),
81
                'password.required'   => trans('auth.passwordRequired'),
82
                'password.min'        => trans('auth.PasswordMin'),
83
                'password.max'        => trans('auth.PasswordMax'),
84
                'role.required'       => trans('auth.roleRequired'),
85
            ]
86
        );
87
88
        if ($validator->fails()) {
89
            return back()->withErrors($validator)->withInput();
0 ignored issues
show
Bug Best Practice introduced by
The expression return back()->withError...validator)->withInput() returns the type Illuminate\Http\RedirectResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
90
        }
91
92
        $ipAddress = new CaptureIpTrait();
93
        $profile = new Profile();
94
95
        $user = User::create([
96
            'name'             => $request->input('name'),
97
            'first_name'       => $request->input('first_name'),
98
            'last_name'        => $request->input('last_name'),
99
            'email'            => $request->input('email'),
100
            'password'         => bcrypt($request->input('password')),
0 ignored issues
show
Bug introduced by
It seems like $request->input('password') can also be of type array; however, parameter $value of bcrypt() 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

100
            'password'         => bcrypt(/** @scrutinizer ignore-type */ $request->input('password')),
Loading history...
101
            'token'            => str_random(64),
102
            'admin_ip_address' => $ipAddress->getClientIp(),
103
            'activated'        => 1,
104
        ]);
105
106
        $user->profile()->save($profile);
107
        $user->attachRole($request->input('role'));
108
        $user->save();
109
110
        return redirect('users')->with('success', trans('usersmanagement.createSuccess'));
0 ignored issues
show
Bug Best Practice introduced by
The expression return redirect('users')...gement.createSuccess')) returns the type Illuminate\Http\RedirectResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
111
    }
112
113
    /**
114
     * Display the specified resource.
115
     *
116
     * @param int $id
117
     *
118
     * @return \Illuminate\Http\Response
119
     */
120
    public function show($id)
121
    {
122
        $user = User::find($id);
123
124
        return view('usersmanagement.show-user')->withUser($user);
0 ignored issues
show
Bug Best Practice introduced by
The expression return view('usersmanage...user')->withUser($user) returns the type Illuminate\View\View which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
125
    }
126
127
    /**
128
     * Show the form for editing the specified resource.
129
     *
130
     * @param int $id
131
     *
132
     * @return \Illuminate\Http\Response
133
     */
134
    public function edit($id)
135
    {
136
        $user = User::findOrFail($id);
137
        $roles = Role::all();
138
139
        foreach ($user->roles as $user_role) {
140
            $currentRole = $user_role;
141
        }
142
143
        $data = [
144
            'user'        => $user,
145
            'roles'       => $roles,
146
            'currentRole' => $currentRole,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $currentRole seems to be defined by a foreach iteration on line 139. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
147
        ];
148
149
        return view('usersmanagement.edit-user')->with($data);
0 ignored issues
show
Bug Best Practice introduced by
The expression return view('usersmanage...dit-user')->with($data) returns the type Illuminate\View\View which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
150
    }
151
152
    /**
153
     * Update the specified resource in storage.
154
     *
155
     * @param \Illuminate\Http\Request $request
156
     * @param int                      $id
157
     *
158
     * @return \Illuminate\Http\Response
159
     */
160
    public function update(Request $request, $id)
161
    {
162
        $currentUser = Auth::user();
0 ignored issues
show
Unused Code introduced by
The assignment to $currentUser is dead and can be removed.
Loading history...
163
        $user = User::find($id);
164
        $emailCheck = ($request->input('email') != '') && ($request->input('email') != $user->email);
165
        $ipAddress = new CaptureIpTrait();
166
167
        if ($emailCheck) {
168
            $validator = Validator::make($request->all(), [
169
                'name'     => 'required|max:255',
170
                'email'    => 'email|max:255|unique:users',
171
                'password' => 'present|confirmed|min:6',
172
            ]);
173
        } else {
174
            $validator = Validator::make($request->all(), [
175
                'name'     => 'required|max:255',
176
                'password' => 'nullable|confirmed|min:6',
177
            ]);
178
        }
179
180
        if ($validator->fails()) {
181
            return back()->withErrors($validator)->withInput();
0 ignored issues
show
Bug Best Practice introduced by
The expression return back()->withError...validator)->withInput() returns the type Illuminate\Http\RedirectResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
182
        }
183
184
        $user->name = $request->input('name');
185
        $user->first_name = $request->input('first_name');
186
        $user->last_name = $request->input('last_name');
187
188
        if ($emailCheck) {
189
            $user->email = $request->input('email');
190
        }
191
192
        if ($request->input('password') != null) {
193
            $user->password = bcrypt($request->input('password'));
0 ignored issues
show
Bug introduced by
It seems like $request->input('password') can also be of type array; however, parameter $value of bcrypt() 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

193
            $user->password = bcrypt(/** @scrutinizer ignore-type */ $request->input('password'));
Loading history...
194
        }
195
196
        $userRole = $request->input('role');
197
        if ($userRole != null) {
198
            $user->detachAllRoles();
199
            $user->attachRole($userRole);
200
        }
201
202
        $user->updated_ip_address = $ipAddress->getClientIp();
203
204
        switch ($userRole) {
205
            case 3:
206
                $user->activated = 0;
207
                break;
208
209
            default:
210
                $user->activated = 1;
211
                break;
212
        }
213
214
        $user->save();
215
216
        return back()->with('success', trans('usersmanagement.updateSuccess'));
0 ignored issues
show
Bug Best Practice introduced by
The expression return back()->with('suc...gement.updateSuccess')) returns the type Illuminate\Http\RedirectResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
217
    }
218
219
    /**
220
     * Remove the specified resource from storage.
221
     *
222
     * @param int $id
223
     *
224
     * @return \Illuminate\Http\Response
225
     */
226
    public function destroy($id)
227
    {
228
        $currentUser = Auth::user();
229
        $user = User::findOrFail($id);
230
        $ipAddress = new CaptureIpTrait();
231
232
        if ($user->id != $currentUser->id) {
0 ignored issues
show
Bug introduced by
Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
233
            $user->deleted_ip_address = $ipAddress->getClientIp();
234
            $user->save();
235
            $user->delete();
236
237
            return redirect('users')->with('success', trans('usersmanagement.deleteSuccess'));
0 ignored issues
show
Bug Best Practice introduced by
The expression return redirect('users')...gement.deleteSuccess')) returns the type Illuminate\Http\RedirectResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
238
        }
239
240
        return back()->with('error', trans('usersmanagement.deleteSelfError'));
0 ignored issues
show
Bug Best Practice introduced by
The expression return back()->with('err...ment.deleteSelfError')) returns the type Illuminate\Http\RedirectResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
241
    }
242
243
    /**
244
     * Method to search the users.
245
     *
246
     * @param Request $request
247
     *
248
     * @return \Illuminate\Http\Response
249
     */
250
    public function search(Request $request)
251
    {
252
        $searchTerm = $request->input('user_search_box');
253
        $searchRules = [
254
            'user_search_box' => 'required|string|max:255',
255
        ];
256
        $searchMessages = [
257
            'user_search_box.required' => 'Search term is required',
258
            'user_search_box.string'   => 'Search term has invalid characters',
259
            'user_search_box.max'      => 'Search term has too many characters - 255 allowed',
260
        ];
261
262
        $validator = Validator::make($request->all(), $searchRules, $searchMessages);
263
264
        if ($validator->fails()) {
265
            return response()->json([
0 ignored issues
show
Bug Best Practice introduced by
The expression return response()->json(...P_UNPROCESSABLE_ENTITY) returns the type Illuminate\Http\JsonResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
266
                json_encode($validator),
267
            ], Response::HTTP_UNPROCESSABLE_ENTITY);
268
        }
269
270
        $results = User::where('id', 'like', $searchTerm.'%')
0 ignored issues
show
Bug introduced by
Are you sure $searchTerm of type null|array can be used in concatenation? ( Ignorable by Annotation )

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

270
        $results = User::where('id', 'like', /** @scrutinizer ignore-type */ $searchTerm.'%')
Loading history...
271
                            ->orWhere('name', 'like', $searchTerm.'%')
272
                            ->orWhere('email', 'like', $searchTerm.'%')->get();
273
274
        // Attach roles to results
275
        foreach ($results as $result) {
276
            $roles = [
277
                'roles' => $result->roles,
278
            ];
279
            $result->push($roles);
280
        }
281
282
        return response()->json([
0 ignored issues
show
Bug Best Practice introduced by
The expression return response()->json(...Http\Response::HTTP_OK) returns the type Illuminate\Http\JsonResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
283
            json_encode($results),
284
        ], Response::HTTP_OK);
285
    }
286
}
287