Php.php 1.8 KB

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