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); } }