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) |
||
| 27 | { |
||
| 28 | if (!Admin::user() || !empty($args) || $this->shouldPassThrough($request)) { |
||
| 29 | return $next($request); |
||
| 30 | } |
||
| 31 | |||
| 32 | if ($this->checkRoutePermission($request)) { |
||
| 33 | return $next($request); |
||
| 34 | } |
||
| 35 | |||
| 36 | if (!Admin::user()->allPermissions()->first(function ($permission) use ($request) { |
||
|
|
|||
| 37 | return $permission->shouldPassThrough($request); |
||
| 38 | })) { |
||
| 39 | Checker::error(); |
||
| 40 | } |
||
| 41 | |||
| 42 | return $next($request); |
||
| 43 | } |
||
| 44 | |||
| 45 | /** |
||
| 46 | * If the route of current request contains a middleware prefixed with 'admin.permission:', |
||
| 47 | * then it has a manually set permission middleware, we need to handle it first. |
||
| 48 | * |
||
| 49 | * @param Request $request |
||
| 50 | * |
||
| 51 | * @return bool |
||
| 52 | */ |
||
| 53 | public function checkRoutePermission(Request $request) |
||
| 73 | |||
| 74 | /** |
||
| 75 | * Determine if the request has a URI that should pass through verification. |
||
| 76 | * |
||
| 77 | * @param \Illuminate\Http\Request $request |
||
| 78 | * |
||
| 79 | * @return bool |
||
| 80 | */ |
||
| 81 | View Code Duplication | protected function shouldPassThrough($request) |
|
| 100 | } |
||
| 101 |
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: