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 |
||
| 11 | { |
||
| 12 | /** |
||
| 13 | * @var string |
||
| 14 | */ |
||
| 15 | protected $middlewarePrefix = 'admin.permission:'; |
||
| 16 | |||
| 17 | /** |
||
| 18 | * Handle an incoming request. |
||
| 19 | * |
||
| 20 | * @param \Illuminate\Http\Request $request |
||
| 21 | * @param \Closure $next |
||
| 22 | * @param array $args |
||
| 23 | * |
||
| 24 | * @return mixed |
||
| 25 | */ |
||
| 26 | public function handle(Request $request, \Closure $next, ...$args) |
||
| 48 | |||
| 49 | /** |
||
| 50 | * If the route of current request contains a middleware prefixed with 'admin.permission:', |
||
| 51 | * then it has a manually set permission middleware, we need to handle it first. |
||
| 52 | * |
||
| 53 | * @param Request $request |
||
| 54 | * |
||
| 55 | * @return bool |
||
| 56 | */ |
||
| 57 | public function checkRoutePermission(Request $request) |
||
| 77 | |||
| 78 | /** |
||
| 79 | * Determine if the request has a URI that should pass through verification. |
||
| 80 | * |
||
| 81 | * @param \Illuminate\Http\Request $request |
||
| 82 | * |
||
| 83 | * @return bool |
||
| 84 | */ |
||
| 85 | View Code Duplication | protected function shouldPassThrough($request) |
|
| 102 | } |
||
| 103 |
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: