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 |
||
| 35 | class Replace extends BaseTask |
||
| 36 | { |
||
| 37 | /** |
||
| 38 | * @var string |
||
| 39 | */ |
||
| 40 | protected $filename; |
||
| 41 | |||
| 42 | /** |
||
| 43 | * @var string|string[] |
||
| 44 | */ |
||
| 45 | protected $from; |
||
| 46 | |||
| 47 | /** |
||
| 48 | * @var integer |
||
| 49 | */ |
||
| 50 | protected $limit = -1; |
||
| 51 | |||
| 52 | /** |
||
| 53 | * @var string|string[] |
||
| 54 | */ |
||
| 55 | protected $to; |
||
| 56 | |||
| 57 | /** |
||
| 58 | * @var string |
||
| 59 | */ |
||
| 60 | protected $regex; |
||
| 61 | |||
| 62 | /** |
||
| 63 | * @param string $filename |
||
| 64 | */ |
||
| 65 | public function __construct($filename) |
||
| 66 | { |
||
| 67 | $this->filename = $filename; |
||
| 68 | } |
||
| 69 | |||
| 70 | /** |
||
| 71 | * @param string $filename |
||
| 72 | * |
||
| 73 | * @return $this |
||
| 74 | */ |
||
| 75 | public function filename($filename) |
||
| 76 | { |
||
| 77 | $this->filename = $filename; |
||
| 78 | return $this; |
||
| 79 | } |
||
| 80 | |||
| 81 | /** |
||
| 82 | * String(s) to be replaced. |
||
| 83 | * |
||
| 84 | * @param string|string[] $from |
||
| 85 | * |
||
| 86 | * @return $this |
||
| 87 | */ |
||
| 88 | public function from($from) |
||
| 89 | { |
||
| 90 | $this->from = $from; |
||
| 91 | return $this; |
||
| 92 | } |
||
| 93 | |||
| 94 | /** |
||
| 95 | * Value(s) to be set as a replacement. |
||
| 96 | * |
||
| 97 | * @param string|string[] $to |
||
| 98 | * |
||
| 99 | * @return $this |
||
| 100 | */ |
||
| 101 | public function to($to) |
||
| 102 | { |
||
| 103 | $this->to = $to; |
||
| 104 | return $this; |
||
| 105 | } |
||
| 106 | |||
| 107 | /** |
||
| 108 | * Regex to match string to be replaced. |
||
| 109 | * |
||
| 110 | * @param string $regex |
||
| 111 | * |
||
| 112 | * @return $this |
||
| 113 | */ |
||
| 114 | public function regex($regex) |
||
| 115 | { |
||
| 116 | $this->regex = $regex; |
||
| 117 | return $this; |
||
| 118 | } |
||
| 119 | |||
| 120 | /** |
||
| 121 | * If used with $this->regexp() how many counts will be replaced |
||
| 122 | * |
||
| 123 | * @param int $limit |
||
| 124 | * |
||
| 125 | * @return $this |
||
| 126 | */ |
||
| 127 | public function limit($limit) |
||
| 132 | |||
| 133 | /** |
||
| 134 | * {@inheritdoc} |
||
| 135 | */ |
||
| 136 | public function run() |
||
| 137 | { |
||
| 160 | } |
||
| 161 |
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.