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 | trait ResourceTrait |
||
13 | { |
||
14 | /** |
||
15 | * @return null|string |
||
16 | */ |
||
17 | public function getId() |
||
18 | { |
||
19 | if ($this instanceof ActiveRecordInterface) { |
||
20 | return (string) $this->getPrimaryKey(); |
||
21 | } |
||
22 | return null; |
||
23 | } |
||
24 | |||
25 | /** |
||
26 | * @return string |
||
27 | */ |
||
28 | public function getType() |
||
29 | { |
||
30 | $reflect = new \ReflectionClass($this); |
||
|
|||
31 | $className = $reflect->getShortName(); |
||
32 | return Inflector::pluralize(Inflector::camel2id($className)); |
||
33 | } |
||
34 | |||
35 | /** |
||
36 | * @param array $fields |
||
37 | * @return array |
||
38 | */ |
||
39 | public function getResourceAttributes(array $fields = []) |
||
40 | { |
||
41 | $attributes = []; |
||
42 | if ($this instanceof Arrayable) { |
||
43 | $fieldDefinitions = $this->fields(); |
||
44 | } else { |
||
45 | $vars = array_keys(\Yii::getObjectVars($this)); |
||
46 | $fieldDefinitions = array_combine($vars, $vars); |
||
47 | } |
||
48 | |||
49 | View Code Duplication | foreach ($this->resolveFields($fieldDefinitions, $fields) as $name => $definition) { |
|
50 | $attributes[$name] = is_string($definition) ? $this->$definition : call_user_func($definition, $this, $name); |
||
51 | } |
||
52 | return $attributes; |
||
53 | } |
||
54 | |||
55 | /** |
||
56 | * @return array |
||
57 | */ |
||
58 | public function getResourceRelationships() |
||
59 | { |
||
60 | $relationships = []; |
||
61 | $fields = []; |
||
62 | if ($this instanceof Arrayable) { |
||
63 | $fields = $this->extraFields(); |
||
64 | } |
||
65 | |||
66 | View Code Duplication | foreach ($this->resolveFields($fields) as $name => $definition) { |
|
67 | $relationships[$name] = is_string($definition) ? $this->$definition : call_user_func($definition, $this, $name); |
||
68 | } |
||
69 | return $relationships; |
||
70 | } |
||
71 | |||
72 | /** |
||
73 | * @param string $name the case sensitive name of the relationship. |
||
74 | * @param $relationship |
||
75 | */ |
||
76 | public function setResourceRelationship($name, $relationship) |
||
87 | |||
88 | /** |
||
89 | * @param array $fields |
||
90 | * @param array $fieldSet |
||
91 | * @return array |
||
92 | */ |
||
93 | protected function resolveFields(array $fields, array $fieldSet = []) |
||
108 | } |
||
109 |
This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.
To visualize
will produce issues in the first and second line, while this second example
will produce no issues.