61 行
1.4 KiB
PHP
61 行
1.4 KiB
PHP
<?php
|
|
|
|
namespace addons\shopro\library\commission;
|
|
|
|
use addons\shopro\model\User as UserModel;
|
|
|
|
/**
|
|
* 邀请码
|
|
*/
|
|
class InviteCode
|
|
{
|
|
/**
|
|
* 生成唯一邀请码
|
|
*/
|
|
public static function generate($userId = 0)
|
|
{
|
|
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
|
do {
|
|
$code = '';
|
|
for ($i = 0; $i < 6; $i++) {
|
|
$code .= $chars[mt_rand(0, strlen($chars) - 1)];
|
|
}
|
|
if ($userId) {
|
|
$code = substr($code, 0, 4) . str_pad($userId % 10000, 4, '0', STR_PAD_LEFT);
|
|
}
|
|
$exists = UserModel::where('invite_code', $code)->find();
|
|
} while ($exists);
|
|
|
|
return $code;
|
|
}
|
|
|
|
/**
|
|
* 为用户生成并保存邀请码
|
|
*/
|
|
public static function ensureForUser($userId)
|
|
{
|
|
$user = UserModel::get($userId);
|
|
if (!$user) {
|
|
return null;
|
|
}
|
|
if (!empty($user->invite_code)) {
|
|
return $user->invite_code;
|
|
}
|
|
$code = self::generate($userId);
|
|
$user->invite_code = $code;
|
|
$user->save();
|
|
return $code;
|
|
}
|
|
|
|
/**
|
|
* 通过邀请码查找用户
|
|
*/
|
|
public static function findUserByCode($code)
|
|
{
|
|
if (empty($code)) {
|
|
return null;
|
|
}
|
|
return UserModel::where('invite_code', strtoupper(trim($code)))->find();
|
|
}
|
|
}
|