PageRenderTime 50ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/src/Faker/Provider/Uuid.php

https://github.com/gobb/Faker
PHP | 48 lines | 30 code | 8 blank | 10 comment | 2 complexity | 20666edb4aaed082c7df679dec649a69 MD5 | raw file
  1. <?php
  2. namespace Faker\Provider;
  3. class Uuid extends \Faker\Provider\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; seed range restricted to 62bit
  12. $seed = mt_rand(0, 2147483647) . '#' . mt_rand(0, 2147483647);
  13. // Hash the seed and convert to a byte array
  14. $val = md5($seed, true);
  15. $byte = array_values(unpack('C16', $val));
  16. // extract fields from byte array
  17. $tLo = ($byte[0] << 24) | ($byte[1] << 16) | ($byte[2] << 8) | $byte[3];
  18. $tMi = ($byte[4] << 8) | $byte[5];
  19. $tHi = ($byte[6] << 8) | $byte[7];
  20. $csLo = $byte[9];
  21. $csHi = $byte[8] & 0x3f | (1 << 7);
  22. // correct byte order for big edian architecture
  23. if (pack('L', 0x6162797A) == pack('N', 0x6162797A)) {
  24. $tLo = (($tLo & 0x000000ff) << 24) | (($tLo & 0x0000ff00) << 8)
  25. | (($tLo & 0x00ff0000) >> 8) | (($tLo & 0xff000000) >> 24);
  26. $tMi = (($tMi & 0x00ff) << 8) | (($tMi & 0xff00) >> 8);
  27. $tHi = (($tHi & 0x00ff) << 8) | (($tHi & 0xff00) >> 8);
  28. }
  29. // apply version number
  30. $tHi &= 0x0fff;
  31. $tHi |= (3 << 12);
  32. // cast to string
  33. $uuid = sprintf(
  34. '%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x',
  35. $tLo, $tMi, $tHi, $csHi, $csLo,
  36. $byte[10], $byte[11], $byte[12], $byte[13], $byte[14], $byte[15]
  37. );
  38. return $uuid;
  39. }
  40. }