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 |
||
| 6 | class Filter |
||
| 7 | { |
||
| 8 | /** @var FilterConfig */ |
||
| 9 | protected $config; |
||
| 10 | |||
| 11 | /** @var FieldConfig */ |
||
| 12 | protected $column; |
||
| 13 | |||
| 14 | /** |
||
| 15 | * Constructor. |
||
| 16 | * |
||
| 17 | * @param FilterConfig $config |
||
| 18 | * @param FieldConfig $column |
||
| 19 | * @param Grid $grid |
||
| 20 | */ |
||
| 21 | public function __construct( |
||
| 22 | FilterConfig $config, |
||
| 23 | FieldConfig $column, |
||
| 24 | Grid $grid |
||
| 25 | ) |
||
| 26 | { |
||
| 27 | $this->config = $config; |
||
| 28 | $this->column = $column; |
||
| 29 | $this->grid = $grid; |
||
|
|
|||
| 30 | } |
||
| 31 | |||
| 32 | /** |
||
| 33 | * Returns input name for the filter. |
||
| 34 | * |
||
| 35 | * @return string |
||
| 36 | */ |
||
| 37 | public function getInputName() |
||
| 38 | { |
||
| 39 | $key = $this->grid->getInputProcessor()->getKey(); |
||
| 40 | $name = $this->config->getId(); |
||
| 41 | return "{$key}[filters][{$name}]"; |
||
| 42 | } |
||
| 43 | |||
| 44 | /** |
||
| 45 | * Returns filter configuration. |
||
| 46 | * |
||
| 47 | * @return FilterConfig |
||
| 48 | */ |
||
| 49 | public function getConfig() |
||
| 53 | |||
| 54 | /** |
||
| 55 | * Returns filters value. |
||
| 56 | * |
||
| 57 | * @return mixed |
||
| 58 | */ |
||
| 59 | View Code Duplication | public function getValue() |
|
| 71 | |||
| 72 | /** |
||
| 73 | * Renders filtering control. |
||
| 74 | * |
||
| 75 | * @return string |
||
| 76 | */ |
||
| 77 | public function render() |
||
| 88 | |||
| 89 | /** |
||
| 90 | * Returns name of template for filtering control. |
||
| 91 | * |
||
| 92 | * @return string |
||
| 93 | */ |
||
| 94 | protected function getTemplate() |
||
| 100 | |||
| 101 | /** |
||
| 102 | * Applies filtering to data source. |
||
| 103 | */ |
||
| 104 | public function apply() |
||
| 139 | } |
||
| 140 |
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: