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 RandomOrgAPI implements RandomOrgAPIInterface |
||
13 | { |
||
14 | /** |
||
15 | * The default Random.org endpoint template. |
||
16 | * |
||
17 | * @var string; |
||
18 | */ |
||
19 | private $endpoint = 'https://api.random.org/json-rpc/1/invoke'; |
||
20 | |||
21 | /** |
||
22 | * The configuration. |
||
23 | * |
||
24 | * @var array |
||
25 | */ |
||
26 | private $configuration; |
||
27 | |||
28 | /** |
||
29 | * The HTTP client. |
||
30 | * |
||
31 | * @var \Http\Client\HttpClient |
||
32 | */ |
||
33 | private $httpClient; |
||
34 | |||
35 | /** |
||
36 | * RandomOrgAPI constructor. |
||
37 | * |
||
38 | * @param array $configuration |
||
39 | */ |
||
40 | 5 | public function __construct(array $configuration = []) |
|
44 | |||
45 | /** |
||
46 | * {@inheritdoc} |
||
47 | */ |
||
48 | 2 | public function withApiKey(string $apikey) |
|
59 | |||
60 | /** |
||
61 | * {@inheritdoc} |
||
62 | */ |
||
63 | 1 | public function withEndPoint(string $endpoint) |
|
70 | |||
71 | /** |
||
72 | * {@inheritdoc} |
||
73 | */ |
||
74 | 1 | public function withHttpClient(HttpClient $client) |
|
81 | |||
82 | /** |
||
83 | * {@inheritdoc} |
||
84 | */ |
||
85 | 1 | public function getEndPoint() |
|
89 | |||
90 | /** |
||
91 | * {@inheritdoc} |
||
92 | */ |
||
93 | 1 | public function getApiKey() |
|
101 | |||
102 | /** |
||
103 | * {@inheritdoc} |
||
104 | */ |
||
105 | public function call(MethodPluginInterface $methodPlugin) |
||
111 | |||
112 | /** |
||
113 | * {@inheritdoc} |
||
114 | */ |
||
115 | public function get(MethodPluginInterface $methodPlugin) |
||
125 | |||
126 | /** |
||
127 | * {@inheritdoc} |
||
128 | */ |
||
129 | public function getData(MethodPluginInterface $methodPlugin) |
||
143 | |||
144 | /** |
||
145 | * {@inheritdoc} |
||
146 | */ |
||
147 | 2 | public function getConfiguration() |
|
151 | |||
152 | /** |
||
153 | * {@inheritdoc} |
||
154 | */ |
||
155 | 1 | public function getHttpClient() |
|
159 | |||
160 | /** |
||
161 | * Validate the response. |
||
162 | * |
||
163 | * @param \Psr\Http\Message\ResponseInterface $response |
||
164 | * |
||
165 | * @return \Exception|ResponseInterface |
||
166 | */ |
||
167 | private function validateResponse(ResponseInterface $response) |
||
207 | } |
||
208 |
It seems like the method you are trying to call exists only in some of the possible types.
Let’s take a look at an example:
Available Fixes
Add an additional type-check:
Only allow a single type to be passed if the variable comes from a parameter: