59 lines
1.4 KiB
PHP
59 lines
1.4 KiB
PHP
<?php
|
||
|
||
namespace app\mzl\common\utils;
|
||
|
||
|
||
class SnGenerator
|
||
{
|
||
/**
|
||
* 生成唯一的用户编号
|
||
*
|
||
* @param int $length 编号长度(6 或 8)
|
||
* @return string
|
||
* @throws Exception
|
||
*/
|
||
public function generateUniqueUserId($length = 6)
|
||
{
|
||
if (!in_array($length, [6, 8])) {
|
||
throw new \Exception("长度必须是 6 或 8 位");
|
||
}
|
||
|
||
$maxAttempts = 100; // 最大尝试次数,避免无限循环
|
||
$attempts = 0;
|
||
|
||
do {
|
||
$userId = $this->generateRandomNumber($length);
|
||
$attempts++;
|
||
if ($attempts > $maxAttempts) {
|
||
throw new \Exception("无法生成唯一的用户编号,请重试");
|
||
}
|
||
} while ($this->isUserIdExists($userId));
|
||
|
||
return $userId;
|
||
}
|
||
|
||
/**
|
||
* 生成随机数字
|
||
*
|
||
* @param int $length 数字长度
|
||
* @return string
|
||
*/
|
||
private function generateRandomNumber($length)
|
||
{
|
||
$min = pow(10, $length - 1); // 最小值,如 6 位是 100000
|
||
$max = pow(10, $length) - 1; // 最大值,如 6 位是 999999
|
||
return (string) mt_rand($min, $max);
|
||
}
|
||
|
||
/**
|
||
* 检查用户编号是否已存在
|
||
*
|
||
* @param string $userId
|
||
* @return bool
|
||
*/
|
||
private function isUserIdExists($userId)
|
||
{
|
||
$userIds = \support\Db::table('hs_users')->pluck('user_sn')->toArray();
|
||
return in_array($userId, $userIds);
|
||
}
|
||
} |