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 |
||
| 21 | class IsUniqueOperation extends Operation |
||
| 22 | { |
||
| 23 | /** |
||
| 24 | * @inheritdoc |
||
| 25 | */ |
||
| 26 | protected function get_controls() |
||
| 27 | { |
||
| 28 | return [ |
||
| 29 | |||
| 30 | self::CONTROL_AUTHENTICATION => true |
||
| 31 | |||
| 32 | ] + parent::get_controls(); |
||
| 33 | } |
||
| 34 | |||
| 35 | /** |
||
| 36 | * @inheritdoc |
||
| 37 | */ |
||
| 38 | protected function validate(ErrorCollection $errors) |
||
| 39 | { |
||
| 40 | $request = $this->request; |
||
| 41 | $username = $request[User::USERNAME]; |
||
| 42 | $email = $request[User::EMAIL]; |
||
| 43 | $uid = $request[User::UID] ?: 0; |
||
| 44 | |||
| 45 | View Code Duplication | if ($username) |
|
| 46 | { |
||
| 47 | if ($this->module->model->select('uid')->where('username = ? AND uid != ?', $username, $uid)->rc) |
||
| 48 | { |
||
| 49 | $errors->add(User::USERNAME, "This username is already used"); |
||
| 50 | } |
||
| 51 | } |
||
| 52 | else |
||
| 53 | { |
||
| 54 | unset($errors[User::USERNAME]); |
||
| 55 | } |
||
| 56 | |||
| 57 | View Code Duplication | if ($email) |
|
| 58 | { |
||
| 59 | if ($this->module->model->select('uid')->where('email = ? AND uid != ?', $email, $uid)->rc) |
||
| 60 | { |
||
| 61 | $errors->add(User::EMAIL, "This email is already used"); |
||
| 62 | } |
||
| 63 | } |
||
| 64 | else |
||
| 65 | { |
||
| 66 | unset($errors[User::EMAIL]); |
||
| 67 | } |
||
| 68 | |||
| 69 | return count($errors) == 0; |
||
| 70 | } |
||
| 71 | |||
| 72 | /** |
||
| 73 | * @inheritdoc |
||
| 74 | */ |
||
| 75 | protected function process() |
||
| 79 | } |
||
| 80 |