You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
185 lines
6.2 KiB
PHP
185 lines
6.2 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\InviteCode;
|
|
|
|
/**
|
|
* Referral-code rules shared by registration and the promotion drawer.
|
|
*/
|
|
class ReferralService
|
|
{
|
|
public const CODE_LENGTH = 8;
|
|
public const CODE_PATTERN = '/^[A-Za-z0-9]{8}$/D';
|
|
private const CODE_ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
|
|
|
|
public static function normalizeCode($value): string
|
|
{
|
|
$value = trim((string) $value);
|
|
return preg_match(self::CODE_PATTERN, $value) === 1 ? $value : '';
|
|
}
|
|
|
|
public static function generateCode(): string
|
|
{
|
|
// The generation lock serializes the check-and-select sequence. A
|
|
// caller that needs an atomic create/update should use codeForUser()
|
|
// or rotateForUser(); this method remains available for legacy code
|
|
// that only needs a fresh candidate value.
|
|
return self::withGenerationLock(static function (): string {
|
|
return self::generateCodeValue();
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Return a user's existing eight-character code or create it atomically.
|
|
*
|
|
* The lock row is deliberately separate from ss_invite_code: legacy
|
|
* installations may contain duplicate/long codes, so adding a unique
|
|
* constraint to that table would make the migration destructive.
|
|
*/
|
|
public static function codeForUser($user): ?InviteCode
|
|
{
|
|
$userId = (int) ($user->id ?? 0);
|
|
if ($userId <= 0) {
|
|
return null;
|
|
}
|
|
|
|
return self::withGenerationLock(static function () use ($userId): InviteCode {
|
|
$existing = InviteCode::where('user_id', $userId)
|
|
->orderBy('id')
|
|
->get()
|
|
->first(static function ($code) {
|
|
return self::normalizeCode($code->code) !== '';
|
|
});
|
|
if ($existing !== null) {
|
|
return $existing;
|
|
}
|
|
|
|
$code = new InviteCode();
|
|
$code->code = self::generateCodeValue();
|
|
$code->user_id = $userId;
|
|
$code->save();
|
|
return $code;
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Generate and persist a replacement code while holding the same lock.
|
|
* This is the safe replacement for legacy callers that used
|
|
* generateCode() followed by save() in separate statements.
|
|
*/
|
|
public static function rotateForUser($user): ?InviteCode
|
|
{
|
|
$userId = (int) ($user->id ?? 0);
|
|
if ($userId <= 0) {
|
|
return null;
|
|
}
|
|
|
|
return self::withGenerationLock(static function () use ($userId): InviteCode {
|
|
$code = InviteCode::where('user_id', $userId)->orderBy('id')->first();
|
|
if ($code === null) {
|
|
$code = new InviteCode();
|
|
$code->user_id = $userId;
|
|
}
|
|
$code->code = self::generateCodeValue();
|
|
$code->save();
|
|
|
|
// Keep the historical one-code-per-user behaviour without
|
|
// touching invitation rows belonging to other users.
|
|
InviteCode::where('user_id', $userId)
|
|
->where('id', '<>', $code->id)
|
|
->delete();
|
|
|
|
return $code;
|
|
});
|
|
}
|
|
|
|
private static function generateCodeValue(): string
|
|
{
|
|
$alphabetLength = strlen(self::CODE_ALPHABET);
|
|
for ($attempt = 0; $attempt < 32; $attempt++) {
|
|
$code = '';
|
|
for ($index = 0; $index < self::CODE_LENGTH; $index++) {
|
|
$code .= self::CODE_ALPHABET[random_int(0, $alphabetLength - 1)];
|
|
}
|
|
|
|
if (!InviteCode::where('code', $code)->exists()) {
|
|
return $code;
|
|
}
|
|
}
|
|
|
|
throw new \RuntimeException('无法生成唯一推广码');
|
|
}
|
|
|
|
private static function withGenerationLock(callable $callback)
|
|
{
|
|
$connection = (new InviteCode())->getConnection();
|
|
try {
|
|
return $connection->transaction(static function () use ($connection, $callback) {
|
|
$lock = $connection->table('referral_code_generation_locks')
|
|
->where('id', 1)
|
|
->lockForUpdate()
|
|
->first();
|
|
if ($lock === null) {
|
|
throw new \RuntimeException(
|
|
'推广码生成锁未初始化,请先导入 web/sql/referral_affiliate_code.sql'
|
|
);
|
|
}
|
|
|
|
return $callback();
|
|
});
|
|
} catch (\Throwable $exception) {
|
|
if ($exception instanceof \RuntimeException
|
|
&& str_starts_with($exception->getMessage(), '推广码生成锁未初始化')) {
|
|
throw $exception;
|
|
}
|
|
throw new \RuntimeException('推广码生成锁不可用,请先导入 web/sql/referral_affiliate_code.sql', 0, $exception);
|
|
}
|
|
}
|
|
|
|
public static function findInvitation($rawCode, $lock = false): ?InviteCode
|
|
{
|
|
$code = self::normalizeCode($rawCode);
|
|
if ($code === '') {
|
|
return null;
|
|
}
|
|
|
|
$query = InviteCode::where('code', $code);
|
|
if ($lock) {
|
|
$query->lockForUpdate();
|
|
}
|
|
|
|
// Existing installations may still have the old case-insensitive
|
|
// column collation until the optional SQL migration is applied. Read
|
|
// the candidate set and compare in PHP so mixed-case codes never
|
|
// resolve to the wrong inviter during that transition.
|
|
foreach ($query->get() as $invitation) {
|
|
if ((string) $invitation->code === $code) {
|
|
return $invitation;
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
public static function registrationCode($query, $cookie = ''): string
|
|
{
|
|
if (is_array($query)) {
|
|
$queryCode = $query['aff'] ?? '';
|
|
$normalized = self::normalizeCode($queryCode);
|
|
if ($normalized !== '') {
|
|
return $normalized;
|
|
}
|
|
|
|
// Keep accepting the historical `code` query parameter while all
|
|
// newly generated links use `aff`.
|
|
$normalized = self::normalizeCode($query['code'] ?? '');
|
|
if ($normalized !== '') {
|
|
return $normalized;
|
|
}
|
|
}
|
|
|
|
return self::normalizeCode($cookie);
|
|
}
|
|
}
|