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 |
||
17 | class QueryResultParser |
||
18 | { |
||
19 | |||
20 | /** |
||
21 | * Parse a payload json string |
||
22 | * |
||
23 | * @param string $payload |
||
24 | * The payload to parse |
||
25 | * @return QueryResult |
||
26 | */ |
||
27 | 2 | public function parseQueryResult(string $payload): QueryResult |
|
52 | |||
53 | 2 | private function assignPropertyValue(ReflectionMethod $method, $destObject, $object, $propertyName) { |
|
59 | |||
60 | 2 | private function getPropertyName(ReflectionMethod $method) { |
|
68 | |||
69 | 2 | private function parseResults(QueryResult $queryResult, $results, bool $isResult) |
|
70 | { |
||
71 | 2 | foreach ($results as $result) { |
|
72 | 2 | $res = new Result(); |
|
73 | 2 | $ref = new ReflectionClass($res); |
|
74 | 2 | $methods = $ref->getMethods(ReflectionMethod::IS_PUBLIC); |
|
75 | 2 | View Code Duplication | foreach ($methods as $method) { |
76 | 2 | if (($propertyName = $this->getPropertyName($method))) { |
|
77 | 2 | if ($propertyName === 'Icon') { |
|
78 | 2 | $res = $this->parseIcon($res, $result->Icon); |
|
79 | 2 | continue; |
|
80 | } |
||
81 | 2 | $this->assignPropertyValue($method, $res, $result, $propertyName); |
|
82 | } |
||
83 | } |
||
84 | 2 | if( $isResult ) { |
|
85 | $queryResult->addResult($res); |
||
86 | } |
||
87 | else { |
||
88 | 2 | $queryResult->addRelatedTopic($res); |
|
89 | } |
||
90 | } |
||
91 | |||
92 | 2 | return $queryResult; |
|
93 | } |
||
94 | |||
95 | 2 | private function parseIcon(Result $result, $icon): Result |
|
118 | |||
119 | 2 | private function parseMeta(QueryResult $result, $meta): QueryResult |
|
123 | } |
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.