| Conditions | 26 |
| Paths | 656 |
| Total Lines | 55 |
| Code Lines | 39 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | <?php |
||
| 37 | public function generate(int $length = 6, int $type = 1): string |
||
| 38 | { |
||
| 39 | // 取字符集数组 |
||
| 40 | $number = range(0, 9); |
||
| 41 | $lowerLetter = range('a', 'z'); |
||
| 42 | $upperLetter = range('A', 'Z'); |
||
| 43 | // 根据type合并字符集 |
||
| 44 | if ($type === 1) { |
||
| 45 | $charset = $number; |
||
| 46 | } elseif ($type === 2) { |
||
| 47 | $charset = $lowerLetter; |
||
| 48 | } elseif ($type === 3) { |
||
| 49 | $charset = $upperLetter; |
||
| 50 | } elseif ($type === 4) { |
||
| 51 | $charset = array_merge($number, $lowerLetter); |
||
| 52 | } elseif ($type === 5) { |
||
| 53 | $charset = array_merge($number, $upperLetter); |
||
| 54 | } elseif ($type === 6) { |
||
| 55 | $charset = array_merge($lowerLetter, $upperLetter); |
||
| 56 | } elseif ($type === 7) { |
||
| 57 | $charset = array_merge($number, $lowerLetter, $upperLetter); |
||
| 58 | } else { |
||
| 59 | $charset = $number; |
||
| 60 | } |
||
| 61 | $str = ''; |
||
| 62 | // 生成字符串 |
||
| 63 | for ($i = 0; $i < $length; $i++) { |
||
| 64 | $str .= $charset[random_int(0, count($charset) - 1)]; |
||
| 65 | // 验证规则 |
||
| 66 | if ($type === 4 && strlen($str) >= 2) { |
||
| 67 | if (!preg_match('/\d+/', $str) || !preg_match('/[a-z]+/', $str)) { |
||
| 68 | $str = substr($str, 0, -1); |
||
| 69 | --$i; |
||
| 70 | } |
||
| 71 | } |
||
| 72 | if ($type === 5 && strlen($str) >= 2) { |
||
| 73 | if (!preg_match('/\d+/', $str) || !preg_match('/[A-Z]+/', $str)) { |
||
| 74 | $str = substr($str, 0, -1); |
||
| 75 | --$i; |
||
| 76 | } |
||
| 77 | } |
||
| 78 | if ($type === 6 && strlen($str) >= 2) { |
||
| 79 | if (!preg_match('/[a-z]+/', $str) || !preg_match('/[A-Z]+/', $str)) { |
||
| 80 | $str = substr($str, 0, -1); |
||
| 81 | --$i; |
||
| 82 | } |
||
| 83 | } |
||
| 84 | if ($type === 7 && strlen($str) >= 3) { |
||
| 85 | if (!preg_match('/\d+/', $str) || !preg_match('/[a-z]+/', $str) || !preg_match('/[A-Z]+/', $str)) { |
||
| 86 | $str = substr($str, 0, -2); |
||
| 87 | $i -= 2; |
||
| 88 | } |
||
| 89 | } |
||
| 90 | } |
||
| 91 | return $str; |
||
| 92 | } |
||
| 94 |