Files
usedcar/app/mzl/common/utils/SnGenerator.php
T
2025-05-14 13:19:23 +08:00

59 lines
1.4 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?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);
}
}