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 |
||
15 | class DefaultErrorRender extends AbstractErrorRender implements ErrorRendererInterface |
||
16 | { |
||
17 | /** |
||
18 | * @param FieldInterface $field |
||
19 | * @return DOMElement |
||
20 | */ |
||
21 | 2 | public function render(FieldInterface $field) |
|
22 | { |
||
23 | 2 | $helpBlock = $this->dom->createElement('span'); |
|
24 | 2 | $helpBlock->setAttribute('class', 'help-block'); |
|
25 | |||
26 | 2 | View Code Duplication | if ($field->hasCustomErrorMessage()) { |
|
|||
27 | 1 | $helpBlock = $this->addCustomErrorMessage($helpBlock, $field); |
|
28 | 1 | } else { |
|
29 | 1 | $helpBlock = $this->addErrorMessages($helpBlock, $field); |
|
30 | } |
||
31 | 2 | return $helpBlock; |
|
32 | } |
||
33 | |||
34 | /** |
||
35 | * @param DOMElement $helpBlock |
||
36 | * @param FieldInterface $field |
||
37 | * @return DOMElement |
||
38 | */ |
||
39 | 1 | View Code Duplication | private function addCustomErrorMessage(DOMElement $helpBlock, FieldInterface $field) |
46 | |||
47 | /** |
||
48 | * @param DOMElement $helpBlock |
||
49 | * @param FieldInterface $field |
||
50 | * @return DOMElement |
||
51 | */ |
||
52 | 1 | View Code Duplication | private function addErrorMessages(DOMElement $helpBlock, FieldInterface $field) |
53 | { |
||
54 | 1 | $messages = $field->getMessages(); |
|
55 | |||
56 | 1 | foreach ($messages as $message) { |
|
57 | 1 | $helpBlock = $this->appendMessage($helpBlock, $message); |
|
58 | 1 | } |
|
59 | 1 | return $helpBlock; |
|
60 | } |
||
61 | |||
62 | /** |
||
63 | * @param DOMElement $helpBlock |
||
64 | * @param $message |
||
65 | * @return DOMElement |
||
66 | */ |
||
67 | 1 | View Code Duplication | private function appendMessage(DOMElement $helpBlock, $message) |
75 | |||
76 | } |
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.