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 |
||
12 | class Https |
||
13 | { |
||
14 | use Utils\RedirectTrait; |
||
15 | |||
16 | const HEADER = 'Strict-Transport-Security'; |
||
17 | |||
18 | /** |
||
19 | * @var bool Add or remove https |
||
20 | */ |
||
21 | private $addHttps; |
||
22 | |||
23 | /** |
||
24 | * @param int One year by default |
||
25 | */ |
||
26 | private $maxAge = 31536000; |
||
27 | |||
28 | /** |
||
29 | * @param bool Whether include subdomains |
||
30 | */ |
||
31 | private $includeSubdomains = false; |
||
32 | |||
33 | /** |
||
34 | * @param bool Whether check the headers |
||
35 | */ |
||
36 | private $checkHttpsForward = false; |
||
37 | |||
38 | /** |
||
39 | * Set basic config. |
||
40 | * |
||
41 | * @param bool $addHttps |
||
42 | */ |
||
43 | public function __construct($addHttps = true) |
||
48 | |||
49 | /** |
||
50 | * Configure the max-age HSTS in seconds. |
||
51 | * |
||
52 | * @param int $maxAge |
||
53 | * |
||
54 | * @return self |
||
55 | */ |
||
56 | public function maxAge($maxAge) |
||
62 | |||
63 | /** |
||
64 | * Configure the includeSubDomains HSTS directive. |
||
65 | * |
||
66 | * @param bool $includeSubdomains |
||
67 | * |
||
68 | * @return self |
||
69 | */ |
||
70 | public function includeSubdomains($includeSubdomains = true) |
||
76 | |||
77 | /** |
||
78 | * Configure whether check the following headers before redirect: |
||
79 | * X-Forwarded-Proto: https |
||
80 | * X-Forwarded-Port: 443. |
||
81 | * |
||
82 | * @param bool $checkHttpsForward |
||
83 | * |
||
84 | * @return self |
||
85 | */ |
||
86 | public function checkHttpsForward($checkHttpsForward = true) |
||
92 | |||
93 | /** |
||
94 | * Execute the middleware. |
||
95 | * |
||
96 | * @param ServerRequestInterface $request |
||
97 | * @param ResponseInterface $response |
||
98 | * @param callable $next |
||
99 | * |
||
100 | * @return ResponseInterface |
||
101 | */ |
||
102 | public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) |
||
144 | } |
||
145 |
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.