Random.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. namespace ba;
  3. class Random
  4. {
  5. /**
  6. * 获取全球唯一标识
  7. * @return string
  8. */
  9. public static function uuid(): string
  10. {
  11. return sprintf(
  12. '%04x%04x-%04x-%04x-%04x-',
  13. mt_rand(0, 0xffff),
  14. mt_rand(0, 0xffff),
  15. mt_rand(0, 0xffff),
  16. mt_rand(0, 0x0fff) | 0x4000,
  17. mt_rand(0, 0x3fff) | 0x8000
  18. ) . substr(md5(uniqid(mt_rand(), true)), 0, 12);
  19. }
  20. /**
  21. * 随机字符生成
  22. * @param string $type 类型 alpha/alnum/numeric/noZero/unique/md5/encrypt/sha1
  23. * @param int $len 长度
  24. * @return string
  25. */
  26. public static function build(string $type = 'alnum', int $len = 8): string
  27. {
  28. switch ($type) {
  29. case 'alpha':
  30. case 'alnum':
  31. case 'numeric':
  32. case 'noZero':
  33. $pool = match ($type) {
  34. 'alpha' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
  35. 'alnum' => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
  36. 'numeric' => '0123456789',
  37. 'noZero' => '123456789',
  38. default => '',
  39. };
  40. return substr(str_shuffle(str_repeat($pool, ceil($len / strlen($pool)))), 0, $len);
  41. case 'unique':
  42. case 'md5':
  43. return md5(uniqid(mt_rand()));
  44. case 'encrypt':
  45. case 'sha1':
  46. return sha1(uniqid(mt_rand(), true));
  47. }
  48. return '';
  49. }
  50. }