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 Dispatcher |
||
11 | { |
||
12 | use Toolkit; |
||
13 | |||
14 | 1 | public function dispatch(string $job, array $params = [], string $service = null, $context = null) |
|
15 | { |
||
16 | 1 | return $this->dispatchAsync($job, $params, $service, $context)->wait(); |
|
17 | } |
||
18 | |||
19 | 1 | public function dispatchAsync(string $job, array $params = [], string $service = null, $context = null) |
|
20 | { |
||
21 | 1 | if ($service === null) { |
|
22 | 1 | $service = $this->getServiceName($job); |
|
23 | } |
||
24 | |||
25 | 1 | $url = $this->getUrl($service, $job); |
|
26 | 1 | View Code Duplication | if (is_array($params) && array_key_exists('eventId', $params)) { |
|
|||
27 | $url .= '/'.$params['eventId']; |
||
28 | } |
||
29 | |||
30 | 1 | if (!$context) { |
|
31 | 1 | $context = $this->getContext(); |
|
32 | } |
||
33 | |||
34 | 1 | $span = $this->get(Tracer::class) |
|
35 | 1 | ->getActiveSpan() |
|
36 | 1 | ->getSpanContext(); |
|
37 | |||
38 | 1 | $response = $this->get(Client::class)->postAsync($url, [ |
|
39 | 'multipart' => [ |
||
40 | [ |
||
41 | 1 | 'name' => 'rpc', |
|
42 | 'contents' => json_encode([ |
||
43 | 1 | 'job' => $job, |
|
44 | 1 | 'params' => $params, |
|
45 | 1 | 'context' => $context, |
|
46 | 'span' => [ |
||
47 | 1 | 'traceId' => $span->getTraceId(), |
|
48 | 1 | 'spanId' => $span->getSpanId(), |
|
49 | ], |
||
50 | ]) |
||
51 | ] |
||
52 | ] |
||
53 | ]); |
||
54 | |||
55 | return $response->then(function ($response) { |
||
56 | 1 | $contents = $response->getBody(); |
|
57 | 1 | if (!$contents) { |
|
58 | throw new Exception("Host $host ($service) is unreachable"); |
||
59 | } |
||
60 | |||
61 | 1 | $result = json_decode($contents); |
|
62 | 1 | if (!$result || !$result->success) { |
|
63 | $exception = new Exception($result->message ?: $contents); |
||
64 | if ($result->trace) { |
||
65 | $exception->remoteTrace = $result->trace; |
||
66 | } |
||
67 | throw $exception; |
||
68 | } |
||
69 | |||
70 | 1 | return $result->data; |
|
71 | 1 | }); |
|
72 | } |
||
73 | |||
74 | 1 | protected function getContext() : array |
|
88 | |||
89 | 1 | protected function getServiceName(string $job) : string |
|
93 | |||
94 | 1 | protected function getUrl(string $service, string $job) : string |
|
99 | |||
100 | public function send(string $job, array $params = [], string $service = null, $context = null) |
||
156 | } |
||
157 |
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.