RandomGenerator.php 814 B

123456789101112131415161718192021222324252627282930313233343536
  1. <?php
  2. namespace Stripe\Util;
  3. /**
  4. * A basic random generator. This is in a separate class so we the generator
  5. * can be injected as a dependency and replaced with a mock in tests.
  6. */
  7. class RandomGenerator
  8. {
  9. /**
  10. * Returns a random value between 0 and $max.
  11. *
  12. * @param float $max (optional)
  13. *
  14. * @return float
  15. */
  16. public function randFloat($max = 1.0)
  17. {
  18. return \mt_rand() / \mt_getrandmax() * $max;
  19. }
  20. /**
  21. * Returns a v4 UUID.
  22. *
  23. * @return string
  24. */
  25. public function uuid()
  26. {
  27. $arr = \array_values(\unpack('N1a/n4b/N1c', \openssl_random_pseudo_bytes(16)));
  28. $arr[2] = ($arr[2] & 0x0fff) | 0x4000;
  29. $arr[3] = ($arr[3] & 0x3fff) | 0x8000;
  30. return \vsprintf('%08x-%04x-%04x-%04x-%04x%08x', $arr);
  31. }
  32. }