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 |
||
| 15 | class ReportController extends Controller |
||
| 16 | { |
||
| 17 | public function index() |
||
| 18 | { |
||
| 19 | $r = UserReport::all(); |
||
| 20 | |||
| 21 | return view('reports.index', [ |
||
| 22 | 'reports' => $r, |
||
| 23 | ]); |
||
| 24 | } |
||
| 25 | |||
| 26 | public function create_game_report($gameid) |
||
| 27 | { |
||
| 28 | $g = Game::whereId($gameid)->first(); |
||
| 29 | |||
| 30 | return view('reports.create', [ |
||
| 31 | 'game' => $g, |
||
| 32 | ]); |
||
| 33 | } |
||
| 34 | |||
| 35 | public function store_game_report(Request $request, $gameid) |
||
| 36 | { |
||
| 37 | $r = new UserReport(); |
||
|
|
|||
| 38 | $r->content_id = $gameid; |
||
| 39 | $r->content_type = 'game'; |
||
| 40 | $r->reason = $request->get('msg'); |
||
| 41 | $r->user_id = \Auth::id(); |
||
| 42 | $r->save(); |
||
| 43 | |||
| 44 | return redirect()->action('ReportController@index_user'); |
||
| 45 | } |
||
| 46 | |||
| 47 | public function index_user() |
||
| 48 | { |
||
| 49 | if (\Auth::check()) { |
||
| 50 | if (\Auth::user()->can('admin-games')) { |
||
| 51 | $ur = UserReport::all(); |
||
| 52 | } else { |
||
| 53 | $ur = UserReport::whereUserId(\Auth::id()); |
||
| 54 | } |
||
| 55 | } else { |
||
| 56 | $ur = null; |
||
| 57 | } |
||
| 58 | |||
| 59 | return view('reports.index', [ |
||
| 60 | 'reports' => $ur, |
||
| 61 | ]); |
||
| 62 | } |
||
| 63 | |||
| 64 | View Code Duplication | public function close_ticket($id) |
|
| 74 | |||
| 75 | View Code Duplication | public function open_ticket($id) |
|
| 85 | |||
| 86 | public function remark_ticket($id) |
||
| 89 | } |
||
| 90 |
This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.
To visualize
will produce issues in the first and second line, while this second example
will produce no issues.