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 HorizontalFormRenderer extends AbstractFormRenderer implements FormRendererInterface |
||
18 | { |
||
19 | 2 | public function __construct() |
|
27 | |||
28 | /** |
||
29 | * @return DOMElement |
||
30 | */ |
||
31 | 2 | View Code Duplication | public function renderFieldLabel() |
39 | |||
40 | /** |
||
41 | * @return DOMElement |
||
42 | */ |
||
43 | 2 | public function renderFieldBlock() |
|
44 | { |
||
45 | 2 | $class = $this->block->getAttribute('class').'form-group'; |
|
46 | 2 | $this->block->setAttribute('class', $class); |
|
47 | |||
48 | 2 | $div = $this->dom->createElement('div'); |
|
49 | 2 | $div->setAttribute('class', 'col-sm-offset-2 col-sm-10'); |
|
50 | |||
51 | 2 | $this->processField($div); |
|
52 | |||
53 | 2 | $this->block->appendChild($div); |
|
54 | |||
55 | 2 | if (!is_null($this->errors)) { |
|
56 | 1 | $this->block->appendChild($this->errors); |
|
57 | 1 | } |
|
58 | |||
59 | 2 | return $this->block; |
|
60 | } |
||
61 | |||
62 | 2 | private function processField(DOMElement $div) |
|
63 | { |
||
64 | 2 | switch (get_class($this->field)) { |
|
65 | 2 | case 'Del\Form\Field\Submit': |
|
66 | 2 | $div->appendChild($this->element); |
|
67 | 2 | break; |
|
68 | 2 | case 'Del\Form\Field\Radio': |
|
69 | 1 | $radioDiv = $this->surroundInDiv($this->element, 'radio'); |
|
70 | 1 | $div->appendChild($radioDiv); |
|
71 | 1 | break; |
|
72 | 2 | case 'Del\Form\Field\CheckBox': |
|
73 | 1 | $checkboxDiv = $this->surroundInDiv($this->element, 'checkbox'); |
|
74 | 1 | $div->appendChild($checkboxDiv); |
|
75 | 1 | break; |
|
76 | 2 | default: |
|
77 | 2 | $this->block->appendChild($this->label); |
|
78 | 2 | $div->setAttribute('class', 'col-sm-10'); |
|
79 | 2 | $div->appendChild($this->element); |
|
80 | 2 | } |
|
81 | 2 | } |
|
82 | |||
83 | /** |
||
84 | * Surround an element in a div with a given class |
||
85 | * |
||
86 | * @param DOMElement $element |
||
87 | * @param $class |
||
88 | * @return DOMElement |
||
89 | */ |
||
90 | 2 | private function surroundInDiv(DOMElement $element, $class) |
|
97 | |||
98 | } |
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.