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 OptionGroup extends DataObject{ |
||
| 9 | |||
| 10 | private static $db = array( |
||
| 11 | 'Title' => 'Varchar(100)' |
||
| 12 | ); |
||
| 13 | |||
| 14 | private static $singular_name = 'Product Option Group'; |
||
| 15 | private static $plural_name = 'Product Option Groups'; |
||
| 16 | private static $description = 'Groups of product options, e.g. size, color, etc'; |
||
| 17 | |||
| 18 | function getCMSFields(){ |
||
| 26 | |||
| 27 | public function requireDefaultRecords() { |
||
| 51 | |||
| 52 | public function getCMSValidator() { |
||
| 55 | |||
| 56 | public function validate(){ |
||
| 57 | $result = parent::validate(); |
||
| 58 | |||
| 59 | $title = $this->Title; |
||
| 60 | $firstChar = substr($title, 0, 1); |
||
| 61 | if(preg_match('/[^a-zA-Z]/', $firstChar)){ |
||
| 62 | $result->error('The first character of the Title can only be a letter', 'bad'); |
||
| 63 | } |
||
| 64 | if(preg_match('/[^a-zA-Z]\s/', $title)){ |
||
| 65 | $result->error('Please only use letters, numbers and spaces in the title', 'bad'); |
||
| 66 | } |
||
| 67 | |||
| 68 | return $result; |
||
| 69 | } |
||
| 70 | |||
| 71 | public function onBeforeDelete(){ |
||
| 72 | parent::onBeforeDelete(); |
||
| 73 | |||
| 74 | //make sure that if we delete this option group, we reassign the group's option items to the 'None' group. |
||
| 75 | $items = OptionItem::get()->filter(array('ProductOptionGroupID' => $this->ID)); |
||
| 76 | |||
| 77 | if(isset($items)){ |
||
| 78 | $noneGroup = OptionGroup::get()->filter(array('Title' => 'Options'))->first(); |
||
| 79 | foreach($items as $item){ |
||
| 80 | $item->ProductOptionGroupID = $noneGroup->ID; |
||
| 81 | $item->write(); |
||
| 82 | } |
||
| 83 | } |
||
| 84 | } |
||
| 85 | |||
| 86 | public function canView($member = false) { |
||
| 89 | |||
| 90 | public function canEdit($member = null) { |
||
| 91 | switch($this->Title){ |
||
| 92 | case 'Options': |
||
| 93 | return false; |
||
| 94 | break; |
||
| 95 | default: |
||
| 96 | return Permission::check('Product_CANCRUD'); |
||
| 97 | break; |
||
| 98 | } |
||
| 99 | |||
| 100 | } |
||
| 101 | |||
| 102 | public function canDelete($member = null) { |
||
| 103 | return $this->canEdit(); |
||
| 104 | } |
||
| 105 | |||
| 106 | public function canCreate($member = null) { |
||
| 109 | |||
| 110 | } |
||
| 111 |
Adding explicit visibility (
private,protected, orpublic) is generally recommend to communicate to other developers how, and from where this method is intended to be used.