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 |
||
| 22 | class InputValidation |
||
| 23 | { |
||
| 24 | const PROFILE_ID_PATTERN = '/^[a-zA-Z-_]+$/'; |
||
| 25 | const COMMON_NAME_PATTERN = '/^[a-zA-Z0-9-_.@]+$/'; |
||
| 26 | const USER_ID_PATTERN = '/^[a-zA-Z0-9-_.@]+$/'; |
||
| 27 | const OTP_KEY_PATTERN = '/^[0-9]{6}$/'; |
||
| 28 | const OTP_SECRET_PATTERN = '/^[A-Z0-9]{16}$/'; |
||
| 29 | const ACCESS_TOKEN_PATTERN = '/^[\x20-\x7E]+$/'; |
||
| 30 | |||
| 31 | View Code Duplication | public static function commonName($commonName) |
|
|
|
|||
| 32 | { |
||
| 33 | if (0 === preg_match(self::COMMON_NAME_PATTERN, $commonName)) { |
||
| 34 | throw new HttpException('invalid value for "common_name"', 400); |
||
| 35 | } |
||
| 36 | if ('..' === $commonName) { |
||
| 37 | throw new HttpException('"common_name" cannot be ".."', 400); |
||
| 38 | } |
||
| 39 | } |
||
| 40 | |||
| 41 | View Code Duplication | public static function userId($userId) |
|
| 42 | { |
||
| 43 | if (0 === preg_match(self::USER_ID_PATTERN, $userId)) { |
||
| 44 | throw new HttpException('invalid value for "user_id"', 400); |
||
| 45 | } |
||
| 46 | if ('..' === $userId) { |
||
| 47 | throw new HttpException('"user_id" cannot be ".."', 400); |
||
| 48 | } |
||
| 49 | } |
||
| 50 | |||
| 51 | public static function disable($disable) |
||
| 57 | |||
| 58 | public static function otpKey($otpKey) |
||
| 64 | |||
| 65 | public static function otpSecret($otpSecret) |
||
| 71 | |||
| 72 | public static function vootToken($vootToken) |
||
| 81 | |||
| 82 | public static function dateTime($dateTime) |
||
| 88 | |||
| 89 | public static function profileId($profileId) |
||
| 90 | { |
||
| 91 | if (0 === preg_match(self::PROFILE_ID_PATTERN, $profileId)) { |
||
| 92 | throw new HttpException('invalid profileId format', 400); |
||
| 93 | } |
||
| 94 | } |
||
| 95 | |||
| 96 | public static function ipAddress($ipAddress) |
||
| 102 | |||
| 103 | public static function ip4($ipAddress) |
||
| 104 | { |
||
| 105 | View Code Duplication | if (false === filter_var($ipAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { |
|
| 109 | |||
| 110 | public static function ip6($ipAddress) |
||
| 116 | |||
| 117 | public static function connectedAt($connectedAt) |
||
| 123 | |||
| 124 | public static function disconnectedAt($disconnectedAt) |
||
| 130 | |||
| 131 | public static function bytesTransferred($bytesTransferred) |
||
| 137 | } |
||
| 138 |
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.