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 |
||
| 11 | class HomeController extends Controller |
||
| 12 | { |
||
| 13 | /** |
||
| 14 | * Create a new controller instance. |
||
| 15 | * |
||
| 16 | * @return void |
||
|
|
|||
| 17 | */ |
||
| 18 | public function __construct() |
||
| 22 | |||
| 23 | /** |
||
| 24 | * Show the application dashboard. |
||
| 25 | * |
||
| 26 | * @return \Illuminate\Http\Response |
||
| 27 | */ |
||
| 28 | public function index() |
||
| 39 | |||
| 40 | View Code Duplication | private function accountSummary() |
|
| 41 | { |
||
| 42 | $list = [ 'total' => 0, 'summary' => []]; |
||
| 43 | $categories = Category::orderBy('name', 'asc')->get(); |
||
| 44 | foreach ($categories as $category) { |
||
| 45 | $count = Account::where('category_id', $category->id)->count(); |
||
| 46 | if ($count) { |
||
| 47 | $list['summary'][]= [ |
||
| 48 | 'count' => $count, |
||
| 49 | 'text' => $category->name |
||
| 50 | ]; |
||
| 51 | $list['total'] += $count; |
||
| 52 | } |
||
| 53 | } |
||
| 54 | return $list; |
||
| 55 | } |
||
| 56 | |||
| 57 | View Code Duplication | private function groupSummary() |
|
| 58 | { |
||
| 59 | $list = [ 'total' => 0, 'summary' => []]; |
||
| 60 | $groups = Group::orderBy('name', 'asc')->get(); |
||
| 61 | foreach ($groups as $group) { |
||
| 62 | $count = Account::where('group_id', $group->id)->count(); |
||
| 63 | $list['summary'][]= [ |
||
| 64 | 'count' => $count, |
||
| 65 | 'text' => $group->name |
||
| 66 | ]; |
||
| 67 | } |
||
| 68 | $list['total'] = $groups->count(); |
||
| 69 | return $list; |
||
| 70 | } |
||
| 71 | |||
| 72 | private function listSummary() |
||
| 73 | { |
||
| 74 | $list = [ 'total' => 0, 'summary' => [] ]; |
||
| 75 | $types = [ 'domain', 'url' ]; |
||
| 76 | foreach ($types as $type) { |
||
| 77 | $count = ProxyListItem::where('type', $type)->count(); |
||
| 78 | if ($count) { |
||
| 79 | $list['summary'][]= [ |
||
| 80 | 'count' => $count, |
||
| 81 | 'text' => "{$type}s" |
||
| 82 | ]; |
||
| 83 | $list['total'] += $count; |
||
| 84 | } |
||
| 85 | } |
||
| 86 | return $list; |
||
| 87 | } |
||
| 88 | |||
| 89 | private function userSummary() |
||
| 90 | { |
||
| 91 | $list = [ 'total' => 0, 'summary' => []]; |
||
| 92 | foreach (User::USER_LEVEL as $id => $level) { |
||
| 93 | $count = User::where('level', $id)->count(); |
||
| 94 | if ($count) { |
||
| 95 | $list['summary'][]= [ |
||
| 96 | 'count' => $count, |
||
| 97 | 'text' => $level['text'] |
||
| 98 | ]; |
||
| 99 | $list['total'] += $count; |
||
| 100 | } |
||
| 101 | } |
||
| 102 | return $list; |
||
| 103 | } |
||
| 104 | } |
||
| 105 |
Adding a
@returnannotation to a constructor is not recommended, since a constructor does not have a meaningful return value.Please refer to the PHP core documentation on constructors.