webman_duanju/extend/ba/Random.php

87 lines
2.5 KiB
PHP

<?php
namespace extend\ba;
class Random
{
/**
* 获取全球唯一标识
* @return string
*/
public static function uuid(): string
{
return sprintf(
'%04x%04x-%04x-%04x-%04x-',
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000
) . substr(md5(uniqid(mt_rand(), true)), 0, 12);
}
/**
* 随机字符生成
* @param string $type 类型 alpha/alnum/numeric/noZero/unique/md5/encrypt/sha1
* @param int $len 长度
* @return string
*/
public static function build(string $type = 'alnum', int $len = 8): string
{
switch ($type) {
case 'alpha':
case 'alnum':
case 'numeric':
case 'noZero':
$pool = match ($type) {
'alpha' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
'alnum' => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
'numeric' => '0123456789',
'noZero' => '123456789',
default => '',
};
return substr(str_shuffle(str_repeat($pool, ceil($len / strlen($pool)))), 0, $len);
case 'unique':
case 'md5':
return md5(uniqid(mt_rand()));
case 'encrypt':
case 'sha1':
return sha1(uniqid(mt_rand(), true));
}
return '';
}
/**
* 生成带随机前缀的唯一ID
* @param int $length ID总长度
* @return string 唯一ID
*/
public static function generateRandomPrefixedId(int $length = 16): string {
$length = min($length, 18);
$prefixLength = 4;
$timestamp = floor(microtime(true) * 1000); // 毫秒级时间戳
$randomPart = '';
// 生成随机前缀
for ($i = 0; $i < $prefixLength; $i++) {
$randomPart .= random_int(0, 9);
}
// 计算剩余长度用于时间戳
$timestampLength = $length - $prefixLength;
$timestampStr = (string) $timestamp;
// 截取或补零时间戳部分
if (strlen($timestampStr) > $timestampLength) {
$timestampStr = substr($timestampStr, -$timestampLength);
} else {
$timestampStr = str_pad($timestampStr, $timestampLength, '0', STR_PAD_LEFT);
}
return $randomPart . $timestampStr;
}
}