Php.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. namespace Drupal\Component\Uuid;
  3. /**
  4. * Generates a UUID v4 (RFC 4122 section 4.4) using PHP code.
  5. *
  6. * @see http://www.rfc-editor.org/rfc/rfc4122.txt
  7. * @see http://www.rfc-editor.org/errata_search.php?rfc=4122&eid=3546
  8. */
  9. class Php implements UuidInterface {
  10. /**
  11. * {@inheritdoc}
  12. */
  13. public function generate() {
  14. // Obtain a random string of 32 hex characters.
  15. $hex = bin2hex(random_bytes(16));
  16. // The variable names $time_low, $time_mid, $time_hi_and_version,
  17. // $clock_seq_hi_and_reserved, $clock_seq_low, and $node correlate to
  18. // the fields defined in RFC 4122 section 4.1.2.
  19. //
  20. // Use characters 0-11 to generate 32-bit $time_low and 16-bit $time_mid.
  21. $time_low = substr($hex, 0, 8);
  22. $time_mid = substr($hex, 8, 4);
  23. // Use characters 12-15 to generate 16-bit $time_hi_and_version.
  24. // The 4 most significant bits are the version number (0100 == 0x4).
  25. // We simply skip character 12 from $hex, and concatenate the strings.
  26. $time_hi_and_version = '4' . substr($hex, 13, 3);
  27. // Use characters 16-17 to generate 8-bit $clock_seq_hi_and_reserved.
  28. // The 2 most significant bits are set to one and zero respectively.
  29. $clock_seq_hi_and_reserved = base_convert(substr($hex, 16, 2), 16, 10);
  30. $clock_seq_hi_and_reserved &= 0b00111111;
  31. $clock_seq_hi_and_reserved |= 0b10000000;
  32. // Use characters 18-19 to generate 8-bit $clock_seq_low.
  33. $clock_seq_low = substr($hex, 18, 2);
  34. // Use characters 20-31 to generate 48-bit $node.
  35. $node = substr($hex, 20);
  36. // Re-combine as a UUID. $clock_seq_hi_and_reserved is still an integer.
  37. $uuid = sprintf('%s-%s-%s-%02x%s-%s',
  38. $time_low, $time_mid, $time_hi_and_version,
  39. $clock_seq_hi_and_reserved, $clock_seq_low,
  40. $node
  41. );
  42. return $uuid;
  43. }
  44. }