Random.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. switch ($type) {
  34. case 'alpha':
  35. $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  36. break;
  37. case 'alnum':
  38. $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  39. break;
  40. case 'numeric':
  41. $pool = '0123456789';
  42. break;
  43. case 'nozero':
  44. $pool = '123456789';
  45. break;
  46. }
  47. return substr(str_shuffle(str_repeat($pool, ceil($len / strlen($pool)))), 0, $len);
  48. case 'unique':
  49. case 'md5':
  50. return md5(uniqid(mt_rand()));
  51. case 'encrypt':
  52. case 'sha1':
  53. return sha1(uniqid(mt_rand(), true));
  54. }
  55. return '';
  56. }
  57. }