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 Permission extends Model |
||
11 | { |
||
12 | /** |
||
13 | * @var array |
||
14 | */ |
||
15 | protected $fillable = ['name', 'slug', 'http_method', 'http_path']; |
||
16 | |||
17 | /** |
||
18 | * @var array |
||
19 | */ |
||
20 | public static $httpMethods = [ |
||
21 | 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS', 'HEAD', |
||
22 | ]; |
||
23 | |||
24 | /** |
||
25 | * Create a new Eloquent model instance. |
||
26 | * |
||
27 | * @param array $attributes |
||
28 | */ |
||
29 | public function __construct(array $attributes = []) |
||
30 | { |
||
31 | $connection = config('admin.database.connection') ?: config('database.default'); |
||
32 | |||
33 | $this->setConnection($connection); |
||
34 | |||
35 | $this->setTable(config('admin.database.permissions_table')); |
||
36 | |||
37 | parent::__construct($attributes); |
||
38 | } |
||
39 | |||
40 | /** |
||
41 | * Permission belongs to many roles. |
||
42 | * |
||
43 | * @return BelongsToMany |
||
44 | */ |
||
45 | View Code Duplication | public function roles() : BelongsToMany |
|
53 | |||
54 | /** |
||
55 | * If request should pass through the current permission. |
||
56 | * |
||
57 | * @param Request $request |
||
58 | * |
||
59 | * @return bool |
||
60 | */ |
||
61 | public function shouldPassThrough(Request $request) : bool |
||
88 | |||
89 | /** |
||
90 | * filter \r |
||
91 | * |
||
92 | * @param string $path |
||
93 | * @return mixed |
||
94 | */ |
||
95 | public function getHttpPathAttribute($path) |
||
99 | |||
100 | /** |
||
101 | * If a request match the specific HTTP method and path. |
||
102 | * |
||
103 | * @param array $match |
||
104 | * @param Request $request |
||
105 | * |
||
106 | * @return bool |
||
107 | */ |
||
108 | protected function matchRequest(array $match, Request $request) : bool |
||
120 | |||
121 | /** |
||
122 | * @param $method |
||
123 | */ |
||
124 | public function setHttpMethodAttribute($method) |
||
130 | |||
131 | /** |
||
132 | * @param $method |
||
133 | * |
||
134 | * @return array |
||
135 | */ |
||
136 | public function getHttpMethodAttribute($method) |
||
144 | |||
145 | /** |
||
146 | * Detach models from the relationship. |
||
147 | * |
||
148 | * @return void |
||
149 | */ |
||
150 | protected static function boot() |
||
158 | } |
||
159 |
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.