PageRenderTime 41ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Faker/Provider/Uuid.php

http://github.com/fzaninotto/Faker
PHP | 58 lines | 39 code | 8 blank | 11 comment | 2 complexity | c1629773446336c81f97f1c78f04131b MD5 | raw file
  1. <?php
  2. namespace Faker\Provider;
  3. class Uuid extends Base
  4. {
  5. /**
  6. * Generate name based md5 UUID (version 3).
  7. * @example '7e57d004-2b97-0e7a-b45f-5387367791cd'
  8. */
  9. public static function uuid()
  10. {
  11. // fix for compatibility with 32bit architecture; each mt_rand call is restricted to 32bit
  12. // two such calls will cause 64bits of randomness regardless of architecture
  13. $seed = mt_rand(0, 2147483647) . '#' . mt_rand(0, 2147483647);
  14. // Hash the seed and convert to a byte array
  15. $val = md5($seed, true);
  16. $byte = array_values(unpack('C16', $val));
  17. // extract fields from byte array
  18. $tLo = ($byte[0] << 24) | ($byte[1] << 16) | ($byte[2] << 8) | $byte[3];
  19. $tMi = ($byte[4] << 8) | $byte[5];
  20. $tHi = ($byte[6] << 8) | $byte[7];
  21. $csLo = $byte[9];
  22. $csHi = $byte[8] & 0x3f | (1 << 7);
  23. // correct byte order for big edian architecture
  24. if (pack('L', 0x6162797A) == pack('N', 0x6162797A)) {
  25. $tLo = (($tLo & 0x000000ff) << 24) | (($tLo & 0x0000ff00) << 8)
  26. | (($tLo & 0x00ff0000) >> 8) | (($tLo & 0xff000000) >> 24);
  27. $tMi = (($tMi & 0x00ff) << 8) | (($tMi & 0xff00) >> 8);
  28. $tHi = (($tHi & 0x00ff) << 8) | (($tHi & 0xff00) >> 8);
  29. }
  30. // apply version number
  31. $tHi &= 0x0fff;
  32. $tHi |= (3 << 12);
  33. // cast to string
  34. $uuid = sprintf(
  35. '%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x',
  36. $tLo,
  37. $tMi,
  38. $tHi,
  39. $csHi,
  40. $csLo,
  41. $byte[10],
  42. $byte[11],
  43. $byte[12],
  44. $byte[13],
  45. $byte[14],
  46. $byte[15]
  47. );
  48. return $uuid;
  49. }
  50. }