Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
1 | <?php |
||
10 | class UserController extends Controller{ |
||
11 | |||
12 | public function __construct(){ |
||
13 | |||
14 | $this->middleware('oauth', ['except' => ['index', 'show']]); |
||
15 | $this->middleware('authorize:' . __CLASS__, ['except' => ['index', 'show']]); |
||
16 | } |
||
17 | |||
18 | public function index(){ |
||
23 | |||
24 | public function store(Request $request){ |
||
25 | |||
26 | $this->validateRequest($request); |
||
27 | |||
28 | $user = User::create([ |
||
29 | 'email' => $request->get('email'), |
||
30 | 'password'=> Hash::make($request->get('password')) |
||
31 | ]); |
||
32 | |||
33 | return $this->success("The user with with id {$user->id} has been created", 201); |
||
34 | } |
||
35 | |||
36 | View Code Duplication | public function show($id){ |
|
37 | |||
38 | $user = User::find($id); |
||
39 | |||
40 | if(!$user){ |
||
41 | return $this->error("The user with {$id} doesn't exist", 404); |
||
42 | } |
||
43 | |||
44 | return $this->success($user, 200); |
||
45 | } |
||
46 | |||
47 | public function update(Request $request, $id){ |
||
64 | |||
65 | View Code Duplication | public function destroy($id){ |
|
66 | |||
67 | $user = User::find($id); |
||
68 | |||
69 | if(!$user){ |
||
70 | return $this->error("The user with {$id} doesn't exist", 404); |
||
71 | } |
||
72 | |||
73 | $user->delete(); |
||
74 | |||
75 | return $this->success("The user with with id {$id} has been deleted", 200); |
||
76 | } |
||
77 | |||
78 | public function validateRequest(Request $request){ |
||
79 | |||
80 | $rules = [ |
||
81 | 'email' => 'required|email|unique:users', |
||
82 | 'password' => 'required|min:6' |
||
83 | ]; |
||
84 | |||
85 | $this->validate($request, $rules); |
||
86 | } |
||
87 | |||
88 | public function isAuthorized(Request $request){ |
||
89 | |||
90 | $resource = "users"; |
||
91 | // $user = User::find($this->getArgs($request)["user_id"]); |
||
92 | |||
93 | return $this->authorizeUser($request, $resource); |
||
94 | } |
||
95 | } |
If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:
If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.