1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
|
class TaiwanRocId { const MALE = 1; const FEMALE = 2;
private $cityMaps = [ 'A' => 10, 'B' => 11, 'C' => 12, 'D' => 13, 'E' => 14, 'F' => 15, 'G' => 16, 'H' => 17, 'J' => 18, 'K' => 19, 'L' => 20, 'M' => 21, 'N' => 22, 'P' => 23, 'Q' => 24, 'R' => 25, 'S' => 26, 'T' => 27, 'U' => 28, 'V' => 29, 'X' => 30, 'Y' => 31, 'W' => 32, 'Z' => 33, 'O' => 35, 'I' => 34, ];
public function generate(string $city = null, int $sex = null, string $mid = null) { $cities = array_keys($this->cityMaps);
if (is_null($city)) { $index = array_rand($cities); $city = $cities[$index]; $cityCode = $this->cityMaps[$city]; } else { $city = strtoupper($city); $cityCode = $this->cityMaps[$city] ?? ''; }
if (is_null($sex)) { $sex = rand(0, 1); }
if (is_null($mid)) { $mid = $this->midRand(); }
if (!in_array($city, $cities)) { throw new \Exception("Invalid city", 1); }
if (!in_array($sex, [self::MALE, self::FEMALE])) { throw new \Exception("Invalid sex", 1); }
$verifyCode = $this->calAll($cityCode, $sex, $mid);
return sprintf('%s%s%s%s', $city, $sex, $mid, $verifyCode); }
public function validate(string $id = '') { [$city, $sex, $mid, $verifyCode] = [ substr($id, 0, 1), substr($id, 1, 1), substr($id, 2, -1), substr($id, -1, 1), ];
return $verifyCode == $this->calAll($this->cityMaps[$city], $sex, $mid); }
private function midRand() { return str_pad(rand(0, 9999999), 7, '0', STR_PAD_LEFT); }
private function calAll($city, $sex, $mid) { $ret = 0; $ret = $this->calCity($city) + $this->calSex($sex) + $this->calMid($mid); $ret = $ret % 10; $ret = 10 - $ret; $ret = $ret % 10;
return $ret; }
private function calCity(int $city) { return substr($city, 0, 1) + substr($city, 1, 1) * 9; }
private function calSex(int $sex) { return $sex * 8; }
private function calMid($mid) { $ret = 0; $len = strlen($mid);
for ($i = 0; $i < $len; $i++) { $ret = $ret + (7 - $i) * substr($mid, $i, 1); }
return $ret; } }
|