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 |
||
20 | View Code Duplication | class CredentialsAuthMiddleware |
|
|
|||
21 | { |
||
22 | const AUTH_NAME = 'credentials'; |
||
23 | |||
24 | /** |
||
25 | * @var string |
||
26 | */ |
||
27 | private $apiKey; |
||
28 | |||
29 | /** |
||
30 | * @var string |
||
31 | */ |
||
32 | private $secret; |
||
33 | |||
34 | /** |
||
35 | * @var null|string |
||
36 | */ |
||
37 | private $userKey; |
||
38 | /** |
||
39 | * @var callable |
||
40 | */ |
||
41 | private $nextHandler; |
||
42 | |||
43 | /** |
||
44 | * @param callable $nextHandler |
||
45 | * @param string $apiKey |
||
46 | * @param string $secret |
||
47 | * @param string|null $userKey |
||
48 | */ |
||
49 | 12 | public function __construct(callable $nextHandler, $apiKey, $secret, $userKey = null) |
|
56 | |||
57 | /** |
||
58 | * Inject credentials information into the query parameters |
||
59 | * |
||
60 | * @param RequestInterface $request |
||
61 | * @param array $options |
||
62 | * |
||
63 | * @return GuzzleResponseInterface |
||
64 | */ |
||
65 | 11 | public function __invoke(RequestInterface $request, array $options) |
|
66 | { |
||
67 | 11 | if ($request->getUri()->getScheme() == 'https' && $options['auth'] == static::AUTH_NAME) { |
|
68 | 2 | $query = isset($options['query']) ? $options['query'] : []; |
|
69 | 2 | $query['client_id'] = $this->userKey ?: $this->apiKey; |
|
70 | 2 | $query['client_secret'] = $this->secret; |
|
71 | 2 | $options['query'] = $query; |
|
72 | 3 | } |
|
73 | 11 | $fn = $this->nextHandler; |
|
74 | 11 | return $fn($request, $options); |
|
75 | } |
||
76 | |||
77 | /** |
||
78 | * @return string |
||
79 | */ |
||
80 | 1 | public function getApiKey() |
|
84 | |||
85 | /** |
||
86 | * @return string |
||
87 | */ |
||
88 | 1 | public function getSecret() |
|
92 | |||
93 | /** |
||
94 | * @return string|null |
||
95 | */ |
||
96 | 1 | public function getUserKey() |
|
100 | |||
101 | /** |
||
102 | * Return a middleware handler function for this Authentication |
||
103 | * |
||
104 | * @param string $apiKey |
||
105 | * @param string $secret |
||
106 | * @param string|null $userKey |
||
107 | * |
||
108 | * @return Closure |
||
109 | */ |
||
110 | public static function middleware($apiKey, $secret, $userKey = null) |
||
116 | } |
||
117 |
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.