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 |
||
13 | trait MagicMethodsTrait |
||
14 | { |
||
15 | protected $_typeMap = []; |
||
16 | |||
17 | 39 | public function __call($name, $arguments) |
|
18 | { |
||
19 | 39 | $callTypeIndex = 3; |
|
20 | 39 | if (substr($name, 0, 2) == "is") { |
|
21 | 4 | $callTypeIndex = 2; |
|
22 | 4 | } |
|
23 | |||
24 | 39 | $callType = substr($name, 0, $callTypeIndex); |
|
25 | 39 | $propertyName = substr($name, $callTypeIndex); |
|
26 | |||
27 | 39 | if (in_array($callType, array('get', 'is')) && count($arguments) == 0) { |
|
28 | 35 | return $this->{$callType}($propertyName); |
|
29 | } |
||
30 | |||
31 | 12 | if (in_array($callType, array('add', 'set')) && count($arguments) == 1) { |
|
32 | 11 | return $this->{$callType}($propertyName, $arguments[0]); |
|
33 | } |
||
34 | |||
35 | 1 | throw new \Exception("The method you tried to call doesn't exist"); |
|
36 | } |
||
37 | |||
38 | 33 | public function __set($name, $value) |
|
39 | { |
||
40 | 33 | View Code Duplication | if (!$this->exists($name) && $this->exists(lcfirst($name))) { |
|
|||
41 | 27 | $name = lcfirst($name); |
|
42 | 27 | } |
|
43 | |||
44 | 33 | $this->$name = $value; |
|
45 | 33 | } |
|
46 | |||
47 | 39 | public function exists($name) |
|
48 | { |
||
49 | 39 | return property_exists($this, $name); |
|
50 | } |
||
51 | |||
52 | 32 | public function get($name) |
|
57 | |||
58 | 10 | public function set($name, $value) |
|
67 | |||
68 | 5 | public function add($name, $value) |
|
85 | |||
86 | 4 | public function is($name) |
|
93 | |||
94 | 2 | public function cast($value, $type) |
|
98 | |||
99 | public function castToExchange($value, $type) |
||
107 | |||
108 | 35 | protected function getValidNameInCorrectCase($names) |
|
120 | |||
121 | /** |
||
122 | * @param $name |
||
123 | * @return string |
||
124 | * @throws \Exception |
||
125 | */ |
||
126 | 38 | protected function getNameInCorrectCase($name) |
|
138 | |||
139 | /** |
||
140 | * @param $name |
||
141 | * @param $value |
||
142 | * @return null |
||
143 | */ |
||
144 | 9 | protected function castValueIfNeeded($name, $value) |
|
154 | } |
||
155 |
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.