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 | trait FooterTrait |
||
| 18 | { |
||
| 19 | |||
| 20 | protected $footnotes = []; |
||
| 21 | protected $footnoteNum = 1; |
||
| 22 | |||
| 23 | /** |
||
| 24 | * @param $text |
||
| 25 | * @return string |
||
| 26 | */ |
||
| 27 | public function parse($text) |
||
| 43 | |||
| 44 | /** |
||
| 45 | * @param $content |
||
| 46 | * @param $blocks |
||
| 47 | * @return string |
||
| 48 | */ |
||
| 49 | protected function applyFooter($content, $blocks) |
||
| 63 | |||
| 64 | /** |
||
| 65 | * Parses a footnote link indicated by `[^`. |
||
| 66 | * @marker [^ |
||
| 67 | * @param $text |
||
| 68 | * @return array |
||
| 69 | */ |
||
| 70 | View Code Duplication | protected function parseFootnoteLink($text) |
|
| 80 | |||
| 81 | /** |
||
| 82 | * @param $block |
||
| 83 | * @return string |
||
| 84 | */ |
||
| 85 | protected function renderFootnoteLink($block) |
||
| 103 | |||
| 104 | /** |
||
| 105 | * identify a line as the beginning of a footnote block |
||
| 106 | * |
||
| 107 | * @param $line |
||
| 108 | * @return false|int |
||
| 109 | */ |
||
| 110 | protected function identifyFootnoteList($line) |
||
| 114 | |||
| 115 | /** |
||
| 116 | * Consume lines for a footnote |
||
| 117 | */ |
||
| 118 | protected function consumeFootnoteList($lines, $current) |
||
| 143 | |||
| 144 | /** |
||
| 145 | * @param $block |
||
| 146 | * @return string |
||
| 147 | */ |
||
| 148 | protected function renderFootnote($block) |
||
| 152 | |||
| 153 | |||
| 154 | } |
This check looks for methods that are used by a trait but not required by it.
To illustrate, let’s look at the following code example
The trait
Idableprovides a methodequalsIdthat in turn relies on the methodgetId(). If this method does not exist on a class mixing in this trait, the method will fail.Adding the
getId()as an abstract method to the trait will make sure it is available.