UsersController::postChangePassword()   B
last analyzed

Complexity

Conditions 6
Paths 22

Size

Total Lines 68
Code Lines 30

Duplication

Lines 23
Ratio 33.82 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 23
loc 68
rs 8.5748
cc 6
eloc 30
nc 22
nop 0

How to fix   Long Method   

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 namespace jlourenco\base\Controllers;
2
3
use App\Http\Controllers\Controller;
4
use Validator;
5
use App\Http\Requests;
6
use Sentinel;
7
use View;
8
use Input;
9
use File;
10
use Activation;
11
use Hash;
12
use Mail;
13
use URL;
14
use Illuminate\Support\Facades\Redirect;
15
use Base;
16
use DB;
17
use Lang;
18
19
class UsersController extends Controller
20
{
21
22
    /**
23
     * Declare the rules for the form validation
24
     *
25
     * @var array
26
     */
27
    protected $validationRules = array(
28
        'first_name'       => 'required|min:3',
29
        'last_name'        => 'required|min:3',
30
        'email'            => 'required|email|unique:User',
31
        'password'         => 'required|between:3,32',
32
        'password_confirm' => 'required|same:password',
33
        'pic'              => 'mimes:jpg,jpeg,bmp,png|max:10000'
34
    );
35
36
    protected $validationRulesAdmin = array(
37
        'gender'           =>  'required|digits_between:0,2',
38
        'first_name'       => 'required|min:3|max:25',
39
        'last_name'        => 'required|min:3|max:25',
40
        'password'         => 'required|between:3,32',
41
        'password_confirm' => 'required|same:password',
42
        'birthday'         =>  'date_format:d/m/Y|before:now',
43
    );
44
45
    protected $genders = [
46
        '0' => 'Male',
47
        '1' => 'Female',
48
        '2' => 'Other'
49
    ];
50
51
    protected $status = [
52
        '0' => 'Inactive',
53
        '1' => 'Active',
54
        '2' => 'Blocked',
55
        '3' => 'To create'
56
    ];
57
58
    /*
59
     * Public section
60
     */
61
62
    /**
63
     * Show a list of all the users.
64
     *
65
     * @return View
66
     */
67
    public function getIndex()
68
    {
69
        // Grab all the users
70
        $users = User::getAllStaff();
71
72
        // Show the page
73
        return View('collaborators', compact('users'));
74
    }
75
76
    /**
77
     * Display specified user profil.
78
     *
79
     * @param  int  $id
0 ignored issues
show
Bug introduced by
There is no parameter named $id. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
80
     * @return Response
81
     */
82
    public function show(User $user)
83
    {
84
        // Show the page
85
        return View('collaborator', compact('user'));
86
    }
87
88
    /**
89
     * get user details and display
90
     */
91
    public function myAccount()
92
    {
93
        $user = Sentinel::getUser();
94
95
        return View::make('public.users.edit', compact('user'));
96
    }
97
98
    /**
99
     * update user details and display
100
     */
101
    public function updateAccount()
102
    {
103
        $user = Sentinel::getUser();
104
105
        //validationRules are declared at beginning
106
        $this->validationRules['email'] = "required|email|unique:users,email,{$user->email},email";
107
108
        if (!$password = Input::get('password')) {
109
            unset($this->validationRules['password']);
110
            unset($this->validationRules['password_confirm']);
111
        }
112
113
        $this->validationRules['birthday'] = 'date_format:d/m/Y|before:now';
114
115
        // Create a new validator instance from our validation rules
116
        $validator = Validator::make(Input::all(), $this->validationRules);
117
118
        // If validation fails, we'll exit the operation now.
119
        if ($validator->fails()) {
120
            // Ooops.. something went wrong
121
            return Redirect::back()->withInput()->withErrors($validator);
122
        }
123
124
        $email = $user->email;
125
126
        // Update the user
127
        $user->first_name = Input::get('first_name');
128
        $user->last_name = Input::get('last_name');
129
        $user->email = Input::get('email');
130
        $user->gender = Input::get('gender');
131
        $user->description = Input::get('description');
132
133 View Code Duplication
        if (Input::get('birthday') != null)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
134
            $user->birthday = \Carbon\Carbon::createFromFormat('d/m/Y', Input::get('birthday'));
135
136
        $passwordChanged = false;
137
138
        // Do we want to update the user password?
139
        if ($password = Input::get('password'))
140
        {
141
            if (Sentinel::validateCredentials($user, [ 'email' => $email, 'password' => Input::get('old-password')]))
142
            {
143
                $passwordChanged = true;
144
                $user->password = Hash::make($password);
145
            }
146 View Code Duplication
            else
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
147
            {
148
                $error = Lang::get('base.auth.wrong_password');
149
                $validator->messages()->add('old-password', Lang::get('base.auth.wrong_password'));
150
151
                // Redirect to the user page
152
                return Redirect::route('profile')->withInput()->withErrors($validator)->with('error', $error);
153
            }
154
        }
155
156
        // is new image uploaded?
157
        if ($file = Input::file('pic')) {
158
            $extension = $file->getClientOriginalExtension() ?: 'png';
159
            $folderName = '/uploads/users/';
160
            $destinationPath = public_path() . $folderName;
161
            $safeName = str_random(10) . '.' . $extension;
162
            $file->move($destinationPath, $safeName);
163
164
            //delete old pic if exists
165
            if (File::exists(public_path() . $folderName . $user->pic))
166
                File::delete(public_path() . $folderName . $user->pic);
167
168
            //save new file path into db
169
            $user->pic = $safeName;
170
171
            Base::Log($user->username . ' (' . $user->first_name . ' ' . $user->last_name . ') changed its profile photo. ');
172
        }
173
174
        // Was the user updated?
175
        if ($user->save()) {
176
            // Prepare the success message
177
            $success = Lang::get('base.auth.account.changed');
178
179
            if ($passwordChanged)
180
            {
181
                Base::Log($user->username . ' (' . $user->first_name . ' ' . $user->last_name . ') changed its password. ');
182
                Mail::queue('emails.account.password-changed', [ 'user' => $user ], function ($m) use ($user) {
183
                    $m->to($user->email, $user->first_name . ' ' . $user->last_name);
184
                    $m->subject(Lang::get('base.mails.password_changed'));
185
                });
186
            }
187
188
            Base::Log($user->username . ' (' . $user->first_name . ' ' . $user->last_name . ') updated the profile. ');
189
190
            // Redirect to the user page
191
            return Redirect::route('profile')->with('success', $success);
192
        }
193
194
        // Prepare the error message
195
        $error = Lang::get('base.base.error');
196
197
        // Redirect to the user page
198
        return Redirect::route('profile')->withInput()->with('error', $error);
199
    }
200
201
    /**
202
     * Show password change form
203
     */
204
    public function getChangePassword()
205
    {
206
        return View::make('public.users.change_password');
207
    }
208
209
    /**
210
     * Change password form processing page.
211
     *
212
     * @param  int      $id
0 ignored issues
show
Bug introduced by
There is no parameter named $id. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
213
     * @return Redirect
214
     */
215
    public function postChangePassword()
216
    {
217
        $user = Sentinel::getUser();
218
219
        $validation = array(
220
            'password'         => 'required|between:3,32',
221
            'password_confirm' => 'required|same:password',
222
        );
223
224
        // Create a new validator instance from our validation rules
225
        $validator = Validator::make(Input::all(), $validation);
226
227
        // If validation fails, we'll exit the operation now.
228
        if ($validator->fails()) {
229
            // Ooops.. something went wrong
230
            return Redirect::back()->withInput()->withErrors($validator);
231
        }
232
233
        try {
234
            // Do we want to update the user password?
235
            $password = Input::get('password');
236
237
            if (Sentinel::validateCredentials($user, [ 'email' => $user->email, 'password' => Input::get('old-password')]))
238
            {
239
                $user->password = Hash::make($password);
240
                $redirect = 'change-password';
241
242
                if ($user->force_new_password)
243
                {
244
                    $user->force_new_password = 0;
245
                    $redirect = 'home';
246
                }
247
248
                // Was the user updated?
249 View Code Duplication
                if ($user->save())
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
250
                {
251
                    // Prepare the success message
252
                    $success = Lang::get('base.auth.account.changed');
253
254
                    Mail::queue('emails.account.password-changed', [ 'user' => $user ], function ($m) use ($user) {
255
                        $m->to($user->email, $user->first_name . ' ' . $user->last_name);
256
                        $m->subject(Lang::get('base.mails.password_changed'));
257
                    });
258
259
                    Base::Log($user->username . ' (' . $user->first_name . ' ' . $user->last_name . ') changed its password account. ');
260
261
                    // Redirect to the user page
262
                    return Redirect::route($redirect)->with('success', $success);
263
                }
264
            }
265 View Code Duplication
            else
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
266
            {
267
                $error = Lang::get('base.auth.wrong_password');
268
                $validator->messages()->add('old-password', Lang::get('base.auth.wrong_password'));
269
270
                // Redirect to the user page
271
                return Redirect::route('change-password')->withInput()->withErrors($validator)->with('error', $error);
272
            }
273
274
            // Prepare the error message
275
        } catch (Exception $e) {
0 ignored issues
show
Bug introduced by
The class jlourenco\base\Controllers\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
276
        }
277
        $error = Lang::get('base.base.error');
278
279
280
        // Redirect to the user page
281
        return Redirect::route('change-password')->withInput()->with('error', $error);
282
    }
283
284
    /*
285
     * Admin section
286
     */
287 View Code Duplication
    public function getAdminIndex()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
288
    {
289
        // Grab all the users
290
        $users = Sentinel::createModel()->where('status', '=', '1')->Get();
291
292
        $possibleStatus = $this->status;
293
        $pending = false;
294
295
        // Show the page
296
        return View('admin.users.list', compact('users', 'possibleStatus', 'pending'));
297
    }
298
299 View Code Duplication
    public function getAdminPending()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
300
    {
301
        // Grab all the users
302
        $users = Sentinel::createModel()->where('last_login', '=', null)->where('status', '=', '0')->Get();
303
304
        $possibleStatus = $this->status;
305
        $pending = true;
306
307
        // Show the page
308
        return View('admin.users.list', compact('users', 'possibleStatus', 'pending'));
309
    }
310
311 View Code Duplication
    public function getAdminBlocked()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
312
    {
313
        // Grab all the users
314
        $users = Sentinel::createModel()->where('status', '=', '2')->Get();
315
316
        $possibleStatus = $this->status;
317
        $pending = true;
318
319
        // Show the page
320
        return View('admin.users.list', compact('users', 'possibleStatus', 'pending'));
321
    }
322
323
    /**
324
     * User update form processing page.
325
     *
326
     * @param  int      $id
327
     * @return Redirect
328
     */
329
    public function adminAccept($id = null)
330
    {
331
        // Get the user information
332
        $user = Sentinel::findById($id);
333
334 View Code Duplication
        if ($user == null || $user->last_login != null || $user->status != 0)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
335
        {
336
            // Prepare the error message
337
            $error = Lang::get('base.auth.not_found');
338
339
            // Redirect to the user management page
340
            return Redirect::route('users.pending')->with('error', $error);
341
        }
342
343
        $user->status = 1;
344
345
        if ($user->save())
346
        {
347
            $activation = Activation::exists($user);
348
349
            if (!$activation)
350
            {
351
                Activation::create($user);
352
353
                $activation = Activation::exists($user);
354
            }
355
356
            if($activation)
357
                Activation::complete($user, $activation->code);
358
359
            Base::TargettedLog($user->username . ' (' . $user->first_name . ' ' . $user->last_name . ') account was accepted. ', $user->id);
360
361
            Mail::queue('emails.account.accepted-by-admin', [ 'user' => $user ], function ($m) use ($user) {
362
                $m->to($user->email, $user->first_name . ' ' . $user->last_name);
363
                $m->subject(Lang::get('base.mails.account_accepted'));
364
            });
365
366
            $success = 'User registration was accepted.';
367
368
            // Redirect to the user page
369
            return Redirect::route('users.pending')->withInput()->with('success', $success);
370
        }
371
372
        $error = Lang::get('base.base.error');
373
374
        // Redirect to the user page
375
        return Redirect::route('users.pending')->withInput()->with('error', $error);
376
    }
377
378
    /**
379
     * User update form processing page.
380
     *
381
     * @param  int      $id
382
     * @return Redirect
383
     */
384
    public function adminRefuse($id = null)
385
    {
386
        // Get the user information
387
        $user = Sentinel::findById($id);
388
389 View Code Duplication
        if ($user == null || $user->last_login != null || $user->status != 0)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
390
        {
391
            // Prepare the error message
392
            $error = Lang::get('base.auth.not_found');
393
394
            // Redirect to the user management page
395
            return Redirect::route('users.pending')->with('error', $error);
396
        }
397
398
        $user->status = 2;
399
400 View Code Duplication
        if ($user->save())
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
401
        {
402
            Base::TargettedLog($user->username . ' (' . $user->first_name . ' ' . $user->last_name . ') account was refused. ', $user->id);
403
404
            if (Base::getSetting('SEND_EMAIL_ON_REFUSE'))
405
                Mail::queue('emails.account.refused-by-admin', [ 'user' => $user ], function ($m) use ($user) {
406
                    $m->to($user->email, $user->first_name . ' ' . $user->last_name);
407
                    $m->subject(Lang::get('base.mails.account_accepted'));
408
                });
409
410
            $success = Lang::get('base.auth.account.rejected');
411
412
            // Redirect to the user page
413
            return Redirect::route('users.pending')->withInput()->with('success', $success);
414
        }
415
416
        $error = Lang::get('base.base.error');
417
418
        // Redirect to the user page
419
        return Redirect::route('users.pending')->withInput()->with('error', $error);
420
    }
421
422
    /**
423
     * Display specified user profile.
424
     *
425
     * @param  int  $id
426
     * @return Response
427
     */
428
    public function adminShow($id)
429
    {
430
        // Get the user information
431
        $user = Sentinel::findUserById($id);
432
433 View Code Duplication
        if ($user == null)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
434
        {
435
            // Prepare the error message
436
            $error = Lang::get('base.auth.not_found');
437
438
            // Redirect to the user management page
439
            return Redirect::route('users')->with('error', $error);
440
        }
441
442
        $possibleStatus = $this->status;
443
444
        $logs = Base::getLogsRepository()->where('created_by', $user->id)->orWhere('target', $user->id)->orderBy('created_at', 'desc')->take(300)->get(['ip', 'log', 'created_at', 'created_by', 'target']);
445
        $ips = Base::getLogsRepository()->where('created_by', $user->id)->where('log', 'LIKE', '%logged%')->orderBy('created_at', 'desc')->select('ip', DB::raw('count(*) as counter'), DB::raw('(SELECT created_at FROM Logs WHERE IP=ip ORDER BY created_at DESC LIMIT 1 ) as created_at'))->groupBy('ip')->take(300)->get();
446
447
        // Show the page
448
        return View('admin.users.show', compact('user', 'possibleStatus', 'logs', 'ips'));
0 ignored issues
show
Bug Best Practice introduced by
The return type of return View('admin.users...atus', 'logs', 'ips')); (Illuminate\View\View|Ill...\Contracts\View\Factory) is incompatible with the return type documented by jlourenco\base\Controlle...rsController::adminShow of type jlourenco\base\Controllers\Response.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
449
    }
450
451
    /**
452
     * Show a list of all the deleted users.
453
     *
454
     * @return View
455
     */
456
    public function getAdminDeletedUsers()
457
    {
458
        // Grab deleted users
459
        $users = Sentinel::createModel()->onlyTrashed()->get();
460
461
        // Show the page
462
        return View('admin.users.deleted', compact('users'));
463
    }
464
465
    /**
466
     * Delete Confirm
467
     *
468
     * @param   int   $id
469
     * @return  View
470
     */
471
    public function getAdminModalDelete($id = null)
472
    {
473
        $confirm_route = $error = null;
474
475
        $title = 'Delete User';
476
        $message = 'Are you sure to delete this user?';
477
478
        // Get user information
479
        $user = Sentinel::findById($id);
480
481
        if ($user == null)
482
        {
483
            // Prepare the error message
484
            $error = Lang::get('base.auth.not_found');
485
            return View('layouts.modal_confirmation', compact('title', 'message', 'error', 'model', 'confirm_route'));
486
        }
487
488
        // Check if we are not trying to delete ourselves
489
        if ($user->id === Sentinel::getUser()->id)  {
490
            // Prepare the error message
491
            $error = Lang::get('base.base.error');
492
493
            return View('layouts.modal_confirmation', compact('title', 'message', 'error', 'model', 'confirm_route'));
494
        }
495
496
        $confirm_route = route('delete/user', ['id' => $user->id]);
497
        return View('layouts.modal_confirmation', compact('title', 'message', 'error', 'model', 'confirm_route'));
498
    }
499
500
    /**
501
     * Delete the given user.
502
     *
503
     * @param  int      $id
504
     * @return Redirect
505
     */
506
    public function getAdminDelete($id = null)
507
    {
508
        // Get user information
509
        $user = Sentinel::findById($id);
510
511 View Code Duplication
        if ($user == null)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
512
        {
513
            // Prepare the error message
514
            $error = Lang::get('base.auth.not_found');
515
516
            // Redirect to the user management page
517
            return Redirect::route('users')->with('error', $error);
518
        }
519
520
        // Check if we are not trying to delete ourselves
521
        if ($user->id === Sentinel::getUser()->id) {
522
            // Prepare the error message
523
            $error = Lang::get('base.base.error');
524
525
            // Redirect to the user management page
526
            return Redirect::route('users')->with('error', $error);
527
        }
528
529
        // Delete the user
530
        //to allow soft deleted, we are performing query on users model instead of Sentinel model
531
        //$user->delete();
0 ignored issues
show
Unused Code Comprehensibility introduced by
84% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
532
        Sentinel::createModel()->destroy($id);
533
534
        // Prepare the success message
535
        $success = Lang::get('base.auth.account.deleted');
536
537
        // Redirect to the user management page
538
        return Redirect::route('users')->with('success', $success);
539
    }
540
541
    /**
542
     * Restore a deleted user.
543
     *
544
     * @param  int      $id
545
     * @return Redirect
546
     */
547
    public function getAdminRestore($id = null)
548
    {
549
        // Get user information
550
        $user = Sentinel::createModel()->withTrashed()->find($id);
551
552
        if ($user == null)
553
        {
554
            // Prepare the error message
555
            $error = Lang::get('base.auth.not_found');
556
557
            // Redirect to the user management page
558
            return Redirect::route('users.deleted')->with('error', $error);
559
        }
560
561
        // Restore the user
562
        $user->restore();
563
564
        // Prepare the success message
565
        $success = Lang::get('base.auth.account.restored');
566
567
        // Redirect to the user management page
568
        return Redirect::route('users.deleted')->with('success', $success);
569
    }
570
571
    /**
572
     * User update.
573
     *
574
     * @param  int  $id
575
     * @return View
576
     */
577
    public function getAdminEdit($id = null)
578
    {
579
        // Get the user information
580
        if($user = Sentinel::findById($id))
581
        {
582
            // Get this user groups
583
            $userRoles = $user->getRoles()->lists('name', 'id')->all();
0 ignored issues
show
Unused Code introduced by
$userRoles is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
584
585
            // Get a list of all the available groups
586
            $roles = Sentinel::getRoleRepository()->all();
0 ignored issues
show
Unused Code introduced by
$roles is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
587
        }
588
        else
589
        {
590
            // Prepare the error message
591
            $error = Lang::get('base.auth.not_found');
592
593
            // Redirect to the user management page
594
            return Redirect::route('users')->with('error', $error);
595
        }
596
597
        $status = $user->status;
598
        $genders = $this->genders;
599
        $statusList = $this->status;
600
601
        $groups = null;
602
        $groups2 = Sentinel::getRoleRepository()->all(['id', 'name']);
603
604
        foreach ($groups2 as $g)
605
        {
606
            $has = false;
607
            foreach ($user->roles as $g2)
608
                if ($g2->id == $g->id)
609
                    $has = true;
610
611
            if (!$has)
612
                $groups[$g->id] = $g->name;
613
        }
614
615
        // Show the page
616
        return View('admin/users/edit', compact('user', 'status', 'genders', 'statusList', 'groups'));
0 ignored issues
show
Bug Best Practice introduced by
The return type of return View('admin/users...tatusList', 'groups')); (Illuminate\View\View|Ill...\Contracts\View\Factory) is incompatible with the return type documented by jlourenco\base\Controlle...ontroller::getAdminEdit of type View.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
617
    }
618
619
    /**
620
     * User update form processing page.
621
     *
622
     * @param  int      $id
623
     * @return Redirect
624
     */
625
    public function postAdminEdit($id = null)
626
    {
627
        // Get the user information
628
        $user = Sentinel::findById($id);
629
630
        if ($user == null)
631
        {
632
            // Prepare the error message
633
            $error = Lang::get('base.auth.not_found');
634
635
            // Redirect to the user management page
636
            return Redirect::route('admin.users.show')->with('error', $error);
637
        }
638
639
        $this->validationRulesAdmin['email'] = "required|email|unique:User,email,{$user->email},email,status,3|max:255";
640
        $this->validationRulesAdmin['username'] = "required|min:3|unique:User,username,{$user->username},username|max:25";
641
642
        // Do we want to update the user password?
643
        if (!$password = Input::get('password')) {
644
            unset($this->validationRulesAdmin['password']);
645
            unset($this->validationRulesAdmin['password_confirm']);
646
        }
647
648
        // Create a new validator instance from our validation rules
649
        $validator = Validator::make(Input::all(), $this->validationRulesAdmin);
650
651
        // If validation fails, we'll exit the operation now.
652
        if ($validator->fails()) {
653
            // Ooops.. something went wrong
654
            return Redirect::back()->withInput()->withErrors($validator);
655
        }
656
657
        try {
658
            // Update the user
659
            $user->gender   = Input::get('gender');
660
            $user->first_name  = Input::get('first_name');
661
            $user->last_name   = Input::get('last_name');
662
            $user->username    = Input::get('username');
663
            $user->email       = Input::get('email');
664
            $user->description = Input::get('description');
665
666
            if (Input::get('force_new_password'))
667
                $user->force_new_password = 1;
668
            else
669
                $user->force_new_password = 0;
670
671 View Code Duplication
            if (Input::get('birthday') != null)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
672
                $user->birthday = \Carbon\Carbon::createFromFormat('d/m/Y', Input::get('birthday'));
673
674
            $password_changed = false;
675
676
            // Do we want to update the user password?
677
            if ($password)
678
            {
679
                $user->password = Hash::make($password);
680
                $password_changed = true;
681
            }
682
683
            // is new image uploaded?
684 View Code Duplication
            if ($file = Input::file('pic'))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
685
            {
686
                $fileName        = $file->getClientOriginalName();
0 ignored issues
show
Unused Code introduced by
$fileName is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
687
                $extension       = $file->getClientOriginalExtension() ?: 'png';
688
689
                if ($extension == 'png' || $extension == 'PNG' || $extension == 'JGP' || $extension == 'jpg' || $extension == 'gif')
690
                {
691
                    $folderName      = '/uploads/users/';
692
                    $destinationPath = public_path() . $folderName;
693
                    $safeName        = str_random(10).'.'.$extension;
694
                    $file->move($destinationPath, $safeName);
695
696
                    //delete old pic if exists
697
                    if(File::exists(public_path() . $folderName . $user->pic))
698
                        File::delete(public_path() . $folderName . $user->pic);
699
700
                    //save new file path into db
701
                    $user->pic   = $safeName;
702
                }
703
            }
704
705
            /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
706
            // Get the current user groups
707
            $userRoles = $user->roles()->lists('id')->all();
708
709
            // Get the selected groups
710
            $selectedRoles = Input::get('groups', array());
711
712
            // Groups comparison between the groups the user currently
713
            // have and the groups the user wish to have.
714
            $rolesToAdd    = array_diff($selectedRoles, $userRoles);
715
            $rolesToRemove = array_diff($userRoles, $selectedRoles);
716
717
            // Assign the user to groups
718
            foreach ($rolesToAdd as $roleId) {
719
                $role = Sentinel::findRoleById($roleId);
720
721
                $role->users()->attach($user);
722
            }
723
724
            // Remove the user from groups
725
            foreach ($rolesToRemove as $roleId) {
726
                $role = Sentinel::findRoleById($roleId);
727
728
                $role->users()->detach($user);
729
            }
730
            */
731
732
            // Activate / De-activate user
733
            $status = $activation = Activation::completed($user);
734
            $currentStatus = Input::get('status');
735
736
            if($currentStatus != $status)
737
            {
738
                if ($currentStatus == 0)
739
                    // Remove existing activation record
740
                    Activation::remove($user);
741
                else
742
                {
743
                    $activation = Activation::exists($user);
744
745
                    if (!$activation)
746
                    {
747
                        Activation::create($user);
748
749
                        $activation = Activation::exists($user);
750
                    }
751
752
                    if($activation)
753
                        Activation::complete($user, $activation->code);
754
                }
755
756
                $user->status = $currentStatus;
757
            }
758
            else
759
                $user->status = $currentStatus;
760
761
            // Was the user updated?
762
            if ($user->save())
763
            {
764
                if ($password_changed && Input::get('send_new_password_email'))
765
                {
766
                    Mail::queue('emails.account.password-changed-by-admin', [ 'user' => $user, 'new_password' => $password ], function ($m) use ($user) {
767
                        $m->to($user->email, $user->first_name . ' ' . $user->last_name);
768
                        $m->subject(Lang::get('base.mails.password_changed'));
769
                    });
770
                }
771
772
                if ($password_changed)
773
                    Base::TargettedLog($user->username . ' (' . $user->first_name . ' ' . $user->last_name . ') password was changed by an admin. ', $user->id);
774
775
                Base::TargettedLog($user->username . ' (' . $user->first_name . ' ' . $user->last_name . ') profile was changed by an admin. ', $user->id);
776
777
                // Prepare the success message
778
                $success = Lang::get('base.auth.user_changed');
779
780
                // Redirect to the user page
781
                return Redirect::route('users.update', $id)->with('success', $success);
782
            }
783
784
        } catch (Exception $e) {
0 ignored issues
show
Bug introduced by
The class jlourenco\base\Controllers\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
785
        }
786
        $error = Lang::get('base.base.error');
787
788
        // Redirect to the user page
789
        return Redirect::route('users.update', $id)->withInput()->with('error', $error);
790
    }
791
792
    /**
793
     * Create new user
794
     *
795
     * @return View
796
     */
797
    public function getAdminCreate()
798
    {
799
        // Get all the available groups
800
        $groups = Sentinel::getRoleRepository()->all();
801
802
        $genders = $this->genders;
803
        $statusList = $this->status;
804
        $user = null;
805
        $status = 0;
806
807
        // Show the page
808
        return View('admin.users.create', compact('groups', 'genders', 'statusList', 'user', 'status'));
809
    }
810
811
    /**
812
     * User create form processing.
813
     *
814
     * @return Redirect
815
     */
816
    public function postAdminCreate()
817
    {
818
        $this->validationRulesAdmin['email'] = "required|email|unique:User";
819
        $this->validationRulesAdmin['username'] = "required|min:3|unique:User|max:25";
820
        $this->validationRulesAdmin['birthday'] = "required|date_format:d/m/Y|before:now";
821
822
        // Create a new validator instance from our validation rules
823
        $validator = Validator::make(Input::all(), $this->validationRulesAdmin);
824
825
        // If validation fails, we'll exit the operation now.
826
        if ($validator->fails()) {
827
            // Ooops.. something went wrong
828
            return Redirect::back()->withInput()->withErrors($validator);
829
        }
830
831
        //check whether use should be activated by default or not
832
        $activate = Input::get('status') != null && Input::get('status') != 0 ? true : false;
833
834
        try {
835
            $birthday = \Carbon\Carbon::createFromFormat('d/m/Y', Input::get('birthday'));
836
837
            // Register the user
838
            $user = Sentinel::register(array(
839
                'gender'   => Input::get('gender'),
840
                'first_name' => Input::get('first_name'),
841
                'last_name'  => Input::get('last_name'),
842
                'username'  => Input::get('username'),
843
                'birthday'   => $birthday,
844
                'email'      => Input::get('email'),
845
                'password'   => Input::get('password'),
846
                'status'   => Input::get('status'),
847
                //'pic'   => isset($safeName)?$safeName:'',
0 ignored issues
show
Unused Code Comprehensibility introduced by
77% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
848
            ), $activate);
849
850
            $user->password = Hash::make(Input::get('password'));
851
            $user->description = Input::get('description');
852
853
            if (Input::get('force_new_password'))
854
                $user->force_new_password = 1;
855
            else
856
                $user->force_new_password = 0;
857
858
            // is new image uploaded?
859 View Code Duplication
            if ($file = Input::file('pic'))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
860
            {
861
                $fileName        = $file->getClientOriginalName();
0 ignored issues
show
Unused Code introduced by
$fileName is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
862
                $extension       = $file->getClientOriginalExtension() ?: 'png';
863
864
                if ($extension == 'png' || $extension == 'PNG' || $extension == 'JGP' || $extension == 'jpg' || $extension == 'gif')
865
                {
866
                    $folderName      = '/uploads/users/';
867
                    $destinationPath = public_path() . $folderName;
868
                    $safeName        = str_random(10).'.'.$extension;
869
                    $file->move($destinationPath, $safeName);
870
871
                    //delete old pic if exists
872
                    if(File::exists(public_path() . $folderName . $user->pic))
873
                        File::delete(public_path() . $folderName . $user->pic);
874
875
                    //save new file path into db
876
                    $user->pic   = $safeName;
877
                }
878
            }
879
880
            $user->save();
881
882
            Base::TargettedLog($user->username . ' (' . $user->first_name . ' ' . $user->last_name . ') account was created by an admin. ', $user->id);
883
884
            if (Input::get('send_new_password_email'))
885
            {
886
                if ($activate)
887
                {
888
                    Mail::queue('emails.account.account-created-by-admin', [ 'user' => $user, 'new_password' => Input::get('password') ], function ($m) use ($user) {
889
                        $m->to($user->email, $user->first_name . ' ' . $user->last_name);
890
                        $m->subject(Lang::get('base.mails.account_created'));
891
                    });
892
                }
893
                else
894
                {
895
                    Mail::queue('emails.account.account-created-by-admin-inactive', [ 'user' => $user, 'new_password' => Input::get('password') ], function ($m2) use ($user) {
896
                        $m2->to($user->email, $user->first_name . ' ' . $user->last_name);
897
                        $m2->subject(Lang::get('base.mails.account_created'));
898
                    });
899
900
                    $activation = Activation::create($user);
901
902
                    // Data to be used on the email view
903
                    $data = array(
904
                        'user'          => $user,
905
                        'activationUrl' => URL::route('activate', [$user->id, $activation->code]),
906
                    );
907
908
                    // Send the activation code through email
909
                    Mail::queue('emails.auth.register-activate', $data, function ($m) use ($user) {
910
                        $m->to($user->email, $user->first_name . ' ' . $user->last_name);
911
                        $m->subject(Lang::get('base.mails.welcome') . ' ' . $user->first_name);
912
                    });
913
914
                }
915
            }
916
917
            //add user to 'User' group
918
            /*$role = Sentinel::findRoleById(Input::get('group'));
0 ignored issues
show
Unused Code Comprehensibility introduced by
46% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
919
            $role->users()->attach($user);
920
921
            //check for activation and send activation mail if not activated by default
922
            if(!Input::get('activate')) {
923
                // Data to be used on the email view
924
                $data = array(
925
                    'user'          => $user,
926
                    'activationUrl' => URL::route('activate', $user->id, Activation::create($user)->code),
927
                );
928
929
                // Send the activation code through email
930
                Mail::send('emails.register-activate', $data, function ($m) use ($user) {
931
                    $m->to($user->email, $user->first_name . ' ' . $user->last_name);
932
                    $m->subject('Welcome ' . $user->first_name);
933
                });
934
            }*/
935
936
            // Redirect to the home page with success menu
937
            return Redirect::route("users")->with('success', Lang::get('base.auth.account.created'));
938
939
        } catch (Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
Bug introduced by
The class jlourenco\base\Controllers\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
940
        }
941
        $error = Lang::get('base.base.error');
942
943
        // Redirect to the user creation page
944
        return Redirect::back()->withInput()->with('error', $error);
945
    }
946
947
    /**
948
     * Remove group Confirm
949
     *
950
     * @param   int   $id
951
     * @param   int   $gid
952
     * @return  View
953
     */
954
    public function getAdminModalRemoveGroup($id = null, $gid = null)
955
    {
956
        $confirm_route = $error = null;
957
958
        $title = 'Remove group';
959
        $message = 'Are you sure to remove this group from this user?';
960
961
        // Get user information
962
        $user = Sentinel::findById($id);
963
964
        if ($user == null)
965
        {
966
            // Prepare the error message
967
            $error = Lang::get('base.auth.not_found');
968
            return View('layouts.modal_confirmation', compact('title', 'message', 'error', 'model', 'confirm_route'));
969
        }
970
971
        // Check if we are not trying to delete ourselves
972
        if ($user->id === Sentinel::getUser()->id + 1)  {
973
            // Prepare the error message
974
            $error = Lang::get('base.base.yourself');
975
976
            return View('layouts.modal_confirmation', compact('title', 'message', 'error', 'model', 'confirm_route'));
977
        }
978
979
        // Get group information
980
        $group = Sentinel::findRoleById($gid);
981
982
        if ($group == null)
983
        {
984
            // Prepare the error message
985
            $error = Lang::get('base.groups.not_found');
986
            return View('layouts.modal_confirmation', compact('title', 'message', 'error', 'model', 'confirm_route'));
987
        }
988
989
        $confirm_route = route('remove/group', ['id' => $user->id, 'gid' => $group->id]);
990
        return View('layouts.modal_confirmation', compact('title', 'message', 'error', 'model', 'confirm_route'));
991
    }
992
993
    /**
994
     * Remove the group from the given user.
995
     *
996
     * @param  int      $id
997
     * @param  int      $gid
998
     * @return Redirect
999
     */
1000 View Code Duplication
    public function getAdminRemoveGroup($id = null, $gid = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1001
    {
1002
        // Get user information
1003
        $user = Sentinel::findById($id);
1004
1005
        if ($user == null)
1006
        {
1007
            // Prepare the error message
1008
            $error = Lang::get('base.auth.not_found');
1009
            return View('layouts.modal_confirmation', compact('title', 'message', 'error', 'model', 'confirm_route'));
0 ignored issues
show
Bug Best Practice introduced by
The return type of return View('layouts.mod...el', 'confirm_route')); (Illuminate\View\View|Ill...\Contracts\View\Factory) is incompatible with the return type documented by jlourenco\base\Controlle...er::getAdminRemoveGroup of type Illuminate\Support\Facades\Redirect.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
1010
        }
1011
1012
        // Check if we are not trying to delete ourselves
1013
        if ($user->id === Sentinel::getUser()->id + 1)  {
1014
            // Prepare the error message
1015
            $error = Lang::get('base.base.yourself');
1016
1017
            return View('layouts.modal_confirmation', compact('title', 'message', 'error', 'model', 'confirm_route'));
0 ignored issues
show
Bug Best Practice introduced by
The return type of return View('layouts.mod...el', 'confirm_route')); (Illuminate\View\View|Ill...\Contracts\View\Factory) is incompatible with the return type documented by jlourenco\base\Controlle...er::getAdminRemoveGroup of type Illuminate\Support\Facades\Redirect.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
1018
        }
1019
1020
        // Get group information
1021
        $group = Sentinel::findRoleById($gid);
1022
1023
        if ($group == null)
1024
        {
1025
            // Prepare the error message
1026
            $error = Lang::get('base.groups.not_found');
1027
            return View('layouts.modal_confirmation', compact('title', 'message', 'error', 'model', 'confirm_route'));
0 ignored issues
show
Bug Best Practice introduced by
The return type of return View('layouts.mod...el', 'confirm_route')); (Illuminate\View\View|Ill...\Contracts\View\Factory) is incompatible with the return type documented by jlourenco\base\Controlle...er::getAdminRemoveGroup of type Illuminate\Support\Facades\Redirect.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
1028
        }
1029
1030
        // Remove the group
1031
        $group->users()->detach($user);
1032
1033
        // Prepare the success message
1034
        $success = Lang::get('base.groups.removed');
1035
1036
        // Redirect to the user management page
1037
        return Redirect::route('users.update', $user->id)->with('success', $success);
1038
    }
1039
1040
    /**
1041
     * Add the group to a given user.
1042
     *
1043
     * @param  int      $id
1044
     * @return Redirect
1045
     */
1046 View Code Duplication
    public function postAdminAddGroup($id = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1047
    {
1048
        // Get user information
1049
        $user = Sentinel::findById($id);
1050
1051
        if ($user == null)
1052
        {
1053
            // Prepare the error message
1054
            $error = Lang::get('base.auth.not_found');
1055
            return View('layouts.modal_confirmation', compact('title', 'message', 'error', 'model', 'confirm_route'));
0 ignored issues
show
Bug Best Practice introduced by
The return type of return View('layouts.mod...el', 'confirm_route')); (Illuminate\View\View|Ill...\Contracts\View\Factory) is incompatible with the return type documented by jlourenco\base\Controlle...ller::postAdminAddGroup of type Illuminate\Support\Facades\Redirect.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
1056
        }
1057
1058
        $gid = Input::get('group');
1059
1060
        if ($gid == null)
1061
        {
1062
            // Prepare the error message
1063
            $error = Lang::get('base.groups.not_found');
1064
            return View('layouts.modal_confirmation', compact('title', 'message', 'error', 'model', 'confirm_route'));
0 ignored issues
show
Bug Best Practice introduced by
The return type of return View('layouts.mod...el', 'confirm_route')); (Illuminate\View\View|Ill...\Contracts\View\Factory) is incompatible with the return type documented by jlourenco\base\Controlle...ller::postAdminAddGroup of type Illuminate\Support\Facades\Redirect.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
1065
        }
1066
1067
        // Get group information
1068
        $group = Sentinel::findRoleById($gid);
1069
1070
        if ($group == null)
1071
        {
1072
            // Prepare the error message
1073
            $error = Lang::get('base.groups.not_found');
1074
            return View('layouts.modal_confirmation', compact('title', 'message', 'error', 'model', 'confirm_route'));
0 ignored issues
show
Bug Best Practice introduced by
The return type of return View('layouts.mod...el', 'confirm_route')); (Illuminate\View\View|Ill...\Contracts\View\Factory) is incompatible with the return type documented by jlourenco\base\Controlle...ller::postAdminAddGroup of type Illuminate\Support\Facades\Redirect.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
1075
        }
1076
1077
        // Remove the group
1078
        $group->users()->attach($user);
1079
1080
        // Prepare the success message
1081
        $success = Lang::get('base.groups.added');
1082
1083
        // Redirect to the user management page
1084
        return Redirect::route('users.update', $user->id)->with('success', $success);
1085
    }
1086
1087
}
1088