Random.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\Math;
  7. use Magento\Framework\Exception\LocalizedException;
  8. use Magento\Framework\Phrase;
  9. /**
  10. * Random data generator
  11. *
  12. * @api
  13. * @since 100.0.2
  14. */
  15. class Random
  16. {
  17. /**#@+
  18. * Frequently used character classes
  19. */
  20. const CHARS_LOWERS = 'abcdefghijklmnopqrstuvwxyz';
  21. const CHARS_UPPERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  22. const CHARS_DIGITS = '0123456789';
  23. /**#@-*/
  24. /**
  25. * Get random string.
  26. *
  27. * @param int $length
  28. * @param null|string $chars
  29. *
  30. * @return string
  31. * @throws LocalizedException
  32. */
  33. public function getRandomString($length, $chars = null)
  34. {
  35. $str = '';
  36. if (null === $chars) {
  37. $chars = self::CHARS_LOWERS.self::CHARS_UPPERS.self::CHARS_DIGITS;
  38. }
  39. $charsMaxKey = mb_strlen($chars) - 1;
  40. for ($i = 0; $i < $length; $i++) {
  41. $str .= $chars[self::getRandomNumber(0, $charsMaxKey)];
  42. }
  43. return $str;
  44. }
  45. /**
  46. * Return a random number in the specified range
  47. *
  48. * @param int $min
  49. * @param int $max
  50. * @return int A random integer value between min (or 0) and max
  51. * @throws LocalizedException
  52. */
  53. public static function getRandomNumber($min = 0, $max = null)
  54. {
  55. if (null === $max) {
  56. $max = mt_getrandmax();
  57. }
  58. if ($max < $min) {
  59. throw new LocalizedException(new Phrase('Invalid range given.'));
  60. }
  61. return random_int($min, $max);
  62. }
  63. /**
  64. * Generate a hash from unique ID.
  65. *
  66. * @param string $prefix
  67. * @return string
  68. * @throws LocalizedException
  69. */
  70. public function getUniqueHash($prefix = '')
  71. {
  72. return $prefix . $this->getRandomString(32);
  73. }
  74. }