Files
hyperf_service/app/Service/ServiceTrait/Common/UserTrait.php
2025-03-03 16:21:38 +08:00

32 lines
716 B
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\Service\ServiceTrait\Common;
use Random\RandomException;
trait UserTrait
{
/**
* @param int $userId
* @return string
* @throws RandomException
*/
protected function generateStableCode(int $userId): string
{
$chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$seed = $userId . random_bytes(16) . microtime(true);
// 使用分段处理避免大数
$hash = hash('sha256', $seed, true);
$code = '';
for ($i=0; $i<8; $i++) {
// 每次取1字节数据0-255
$byte = ord($hash[$i]);
$code .= $chars[$byte % 62];
}
return $code;
}
}