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 |
||
11 | trait JSONRepresentationTrait |
||
12 | { |
||
13 | /** |
||
14 | * @param PagerDutyEntityInterface $pagerDutyEntity |
||
15 | * |
||
16 | * @return string |
||
17 | */ |
||
18 | 4 | public function persistRepresentJSON(PagerDutyEntityInterface $pagerDutyEntity) |
|
25 | |||
26 | /** |
||
27 | * @param string $jsonString |
||
28 | * @param PagerDutyEntityInterface|null $pagerDutyEntity |
||
29 | * |
||
30 | * @return PagerDutyEntityInterface |
||
31 | */ |
||
32 | public function loadRepresentJSON($jsonString, PagerDutyEntityInterface $pagerDutyEntity = null) |
||
|
|||
33 | { |
||
34 | return $this->loadRepresentObj( |
||
35 | json_decode($jsonString) |
||
36 | ); |
||
37 | } |
||
38 | |||
39 | /** |
||
40 | * @param PagerDutyEntityInterface $pagerDutyEntity |
||
41 | * |
||
42 | * @return stdClass |
||
43 | */ |
||
44 | 4 | public function persistRepresentObj(PagerDutyEntityInterface $pagerDutyEntity) |
|
45 | { |
||
46 | 4 | $representObject = new stdClass(); |
|
47 | |||
48 | 4 | $objArray = (array) $pagerDutyEntity; |
|
49 | 4 | foreach ($objArray as $key => $value) { |
|
50 | 4 | if (null === $value) { |
|
51 | 4 | continue; |
|
52 | } |
||
53 | 4 | $key = $this->cameCaseTransformToUnderscores($key); |
|
54 | 4 | $representObject->$key = $value; |
|
55 | 4 | } |
|
56 | |||
57 | 4 | return $representObject; |
|
58 | } |
||
59 | |||
60 | /** |
||
61 | * @param stdClass $obj |
||
62 | * @param PagerDutyEntityInterface|null $pagerDutyEntity |
||
63 | */ |
||
64 | View Code Duplication | public function loadRepresentObj(stdClass $obj, PagerDutyEntityInterface $pagerDutyEntity = null) |
|
65 | { |
||
66 | if (null === $pagerDutyEntity) { |
||
67 | $entityClassName = static::getEntityClassName(); |
||
68 | $pagerDutyEntity = new $entityClassName(); |
||
69 | } |
||
70 | $objArray = (array) $obj; |
||
71 | foreach ($objArray as $key => $value) { |
||
72 | $key = $this->underscoresTransformToCameCase($key); |
||
73 | $representObject->$key = $value; |
||
74 | } |
||
75 | } |
||
76 | |||
77 | /** |
||
78 | * Decamelize str cameCase string to underscored. |
||
79 | * |
||
80 | * @param string $cameCaseStr |
||
81 | * |
||
82 | * @return string |
||
83 | */ |
||
84 | 4 | protected function cameCaseTransformToUnderscores($cameCaseStr) |
|
88 | |||
89 | /** |
||
90 | * Decamelize str cameCase string to underscored. |
||
91 | * |
||
92 | * @param string $underscores |
||
93 | * |
||
94 | * @return string |
||
95 | */ |
||
96 | protected function underscoresTransformToCameCase($underscores) |
||
109 | } |
||
110 |
This check looks from parameters that have been defined for a function or method, but which are not used in the method body.