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 |
||
18 | class CheckAuthenticationMiddleware implements MiddlewareInterface |
||
19 | { |
||
20 | const AUTHORIZATION_HEADER = 'Authorization'; |
||
21 | |||
22 | /** |
||
23 | * @var TranslatorInterface |
||
24 | */ |
||
25 | private $translator; |
||
26 | /** |
||
27 | * @var JWTServiceInterface |
||
28 | */ |
||
29 | private $jwtService; |
||
30 | /** |
||
31 | * @var LoggerInterface |
||
32 | */ |
||
33 | private $logger; |
||
34 | |||
35 | /** |
||
36 | * CheckAuthenticationMiddleware constructor. |
||
37 | * @param JWTServiceInterface|JWTService $jwtService |
||
38 | * @param TranslatorInterface $translator |
||
39 | * @param LoggerInterface $logger |
||
40 | * |
||
41 | * @Inject({JWTService::class, "translator", "Logger_Shlink"}) |
||
42 | */ |
||
43 | 6 | public function __construct( |
|
52 | |||
53 | /** |
||
54 | * Process an incoming request and/or response. |
||
55 | * |
||
56 | * Accepts a server-side request and a response instance, and does |
||
57 | * something with them. |
||
58 | * |
||
59 | * If the response is not complete and/or further processing would not |
||
60 | * interfere with the work done in the middleware, or if the middleware |
||
61 | * wants to delegate to another process, it can use the `$out` callable |
||
62 | * if present. |
||
63 | * |
||
64 | * If the middleware does not return a value, execution of the current |
||
65 | * request is considered complete, and the response instance provided will |
||
66 | * be considered the response to return. |
||
67 | * |
||
68 | * Alternately, the middleware may return a response instance. |
||
69 | * |
||
70 | * Often, middleware will `return $out();`, with the assumption that a |
||
71 | * later middleware will return a response. |
||
72 | * |
||
73 | * @param Request $request |
||
74 | * @param Response $response |
||
75 | * @param null|callable $out |
||
76 | * @return null|Response |
||
77 | */ |
||
78 | 6 | public function __invoke(Request $request, Response $response, callable $out = null) |
|
136 | |||
137 | 2 | protected function createTokenErrorResponse() |
|
150 | } |
||
151 |
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.