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 |
||
| 8 | class Checkbox_Field extends Field { |
||
| 9 | |||
| 10 | /** |
||
| 11 | * @{inheritDoc} |
||
| 12 | */ |
||
| 13 | protected $default_value = false; |
||
| 14 | |||
| 15 | /** |
||
| 16 | * The value that is saved in the database when |
||
| 17 | * this checkbox field is enabled. |
||
| 18 | * |
||
| 19 | * @var string |
||
| 20 | */ |
||
| 21 | protected $option_value = 'yes'; |
||
| 22 | |||
| 23 | /** |
||
| 24 | * Get the option value. |
||
| 25 | * |
||
| 26 | * @return string |
||
| 27 | */ |
||
| 28 | public function get_option_value() { |
||
| 31 | |||
| 32 | /** |
||
| 33 | * Set the option value. |
||
| 34 | * |
||
| 35 | * @param string $value New value |
||
| 36 | * @return Field $this |
||
| 37 | */ |
||
| 38 | public function set_option_value( $value ) { |
||
| 42 | |||
| 43 | /** |
||
| 44 | * Load the field value from an input array based on it's name. |
||
| 45 | * If not enabled, set to empty string for easier data querying. |
||
| 46 | * |
||
| 47 | * @param array $input Array of field names and values. |
||
| 48 | */ |
||
| 49 | public function set_value_from_input( $input ) { |
||
| 55 | |||
| 56 | /** |
||
| 57 | * Return a differently formatted value for end-users |
||
| 58 | * |
||
| 59 | * @return mixed |
||
| 60 | */ |
||
| 61 | public function get_formatted_value() { |
||
| 64 | |||
| 65 | /** |
||
| 66 | * Returns an array that holds the field data, suitable for JSON representation. |
||
| 67 | * In addition to default data, option value and label are added. |
||
| 68 | * |
||
| 69 | * @param bool $load Should the value be loaded from the database or use the value from the current instance. |
||
| 70 | * @return array |
||
| 71 | */ |
||
| 72 | View Code Duplication | public function to_json( $load ) { |
|
| 82 | |||
| 83 | /** |
||
| 84 | * Get the field label. |
||
| 85 | * Label here is empty because it is displayed in the front-end. |
||
| 86 | * |
||
| 87 | * @return string Label of the field. |
||
| 88 | */ |
||
| 89 | public function get_label() { |
||
| 92 | |||
| 93 | /** |
||
| 94 | * Whether this field is required. |
||
| 95 | * A single checkbox field is non-required by design. |
||
| 96 | * |
||
| 97 | * @return boolean false |
||
| 98 | */ |
||
| 99 | public function is_required() { |
||
| 102 | } |
||
| 103 |