buildadmin/extend/ba/Random.php

54 lines
1.6 KiB
PHP
Raw Normal View History

2022-02-25 17:09:03 +00:00
<?php
2022-02-27 20:07:40 +00:00
namespace ba;
2022-02-25 17:09:03 +00:00
class Random
{
/**
* 获取全球唯一标识
* @return string
*/
2022-10-29 10:56:30 +00:00
public static function uuid(): string
2022-02-25 17:09:03 +00:00
{
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);
}
2022-03-11 17:29:06 +00:00
/**
* 随机字符生成
* @param string $type 类型 alpha/alnum/numeric/noZero/unique/md5/encrypt/sha1
2022-03-11 17:29:06 +00:00
* @param int $len 长度
* @return string
*/
2022-08-23 15:01:30 +00:00
public static function build(string $type = 'alnum', int $len = 8): string
2022-03-11 17:29:06 +00:00
{
switch ($type) {
case 'alpha':
case 'alnum':
case 'numeric':
case 'noZero':
$pool = match ($type) {
'alpha' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
'alnum' => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
'numeric' => '0123456789',
'noZero' => '123456789',
default => '',
};
2022-03-11 17:29:06 +00:00
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));
}
2022-08-23 15:01:30 +00:00
return '';
2022-03-11 17:29:06 +00:00
}
2022-02-25 17:09:03 +00:00
}