UuidV7.php 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Uid;
  11. /**
  12. * A v7 UUID is lexicographically sortable and contains a 48-bit timestamp and 74 extra unique bits.
  13. *
  14. * Within the same millisecond, monotonicity is ensured by incrementing the random part by a random increment.
  15. *
  16. * @author Nicolas Grekas <p@tchwork.com>
  17. */
  18. class UuidV7 extends Uuid implements TimeBasedUidInterface
  19. {
  20. protected const TYPE = 7;
  21. private static string $time = '';
  22. private static array $rand = [];
  23. private static string $seed;
  24. private static array $seedParts;
  25. private static int $seedIndex = 0;
  26. public function __construct(?string $uuid = null)
  27. {
  28. if (null === $uuid) {
  29. $this->uid = static::generate();
  30. } else {
  31. parent::__construct($uuid, true);
  32. }
  33. }
  34. public function getDateTime(): \DateTimeImmutable
  35. {
  36. $time = substr($this->uid, 0, 8).substr($this->uid, 9, 4);
  37. $time = \PHP_INT_SIZE >= 8 ? (string) hexdec($time) : BinaryUtil::toBase(hex2bin($time), BinaryUtil::BASE10);
  38. if (4 > \strlen($time)) {
  39. $time = '000'.$time;
  40. }
  41. return \DateTimeImmutable::createFromFormat('U.v', substr_replace($time, '.', -3, 0));
  42. }
  43. public static function generate(?\DateTimeInterface $time = null): string
  44. {
  45. if (null === $mtime = $time) {
  46. $time = microtime(false);
  47. $time = substr($time, 11).substr($time, 2, 3);
  48. } elseif (0 > $time = $time->format('Uv')) {
  49. throw new \InvalidArgumentException('The timestamp must be positive.');
  50. }
  51. if ($time > self::$time || (null !== $mtime && $time !== self::$time)) {
  52. randomize:
  53. self::$rand = unpack('n*', isset(self::$seed) ? random_bytes(10) : self::$seed = random_bytes(16));
  54. self::$rand[1] &= 0x03FF;
  55. self::$time = $time;
  56. } else {
  57. // Within the same ms, we increment the rand part by a random 24-bit number.
  58. // Instead of getting this number from random_bytes(), which is slow, we get
  59. // it by sha512-hashing self::$seed. This produces 64 bytes of entropy,
  60. // which we need to split in a list of 24-bit numbers. unpack() first splits
  61. // them into 16 x 32-bit numbers; we take the first byte of each of these
  62. // numbers to get 5 extra 24-bit numbers. Then, we consume those numbers
  63. // one-by-one and run this logic every 21 iterations.
  64. // self::$rand holds the random part of the UUID, split into 5 x 16-bit
  65. // numbers for x86 portability. We increment this random part by the next
  66. // 24-bit number in the self::$seedParts list and decrement self::$seedIndex.
  67. if (!self::$seedIndex) {
  68. $s = unpack('l*', self::$seed = hash('sha512', self::$seed, true));
  69. $s[] = ($s[1] >> 8 & 0xFF0000) | ($s[2] >> 16 & 0xFF00) | ($s[3] >> 24 & 0xFF);
  70. $s[] = ($s[4] >> 8 & 0xFF0000) | ($s[5] >> 16 & 0xFF00) | ($s[6] >> 24 & 0xFF);
  71. $s[] = ($s[7] >> 8 & 0xFF0000) | ($s[8] >> 16 & 0xFF00) | ($s[9] >> 24 & 0xFF);
  72. $s[] = ($s[10] >> 8 & 0xFF0000) | ($s[11] >> 16 & 0xFF00) | ($s[12] >> 24 & 0xFF);
  73. $s[] = ($s[13] >> 8 & 0xFF0000) | ($s[14] >> 16 & 0xFF00) | ($s[15] >> 24 & 0xFF);
  74. self::$seedParts = $s;
  75. self::$seedIndex = 21;
  76. }
  77. self::$rand[5] = 0xFFFF & $carry = self::$rand[5] + 1 + (self::$seedParts[self::$seedIndex--] & 0xFFFFFF);
  78. self::$rand[4] = 0xFFFF & $carry = self::$rand[4] + ($carry >> 16);
  79. self::$rand[3] = 0xFFFF & $carry = self::$rand[3] + ($carry >> 16);
  80. self::$rand[2] = 0xFFFF & $carry = self::$rand[2] + ($carry >> 16);
  81. self::$rand[1] += $carry >> 16;
  82. if (0xFC00 & self::$rand[1]) {
  83. if (\PHP_INT_SIZE >= 8 || 10 > \strlen($time = self::$time)) {
  84. $time = (string) (1 + $time);
  85. } elseif ('999999999' === $mtime = substr($time, -9)) {
  86. $time = (1 + substr($time, 0, -9)).'000000000';
  87. } else {
  88. $time = substr_replace($time, str_pad(++$mtime, 9, '0', \STR_PAD_LEFT), -9);
  89. }
  90. goto randomize;
  91. }
  92. $time = self::$time;
  93. }
  94. if (\PHP_INT_SIZE >= 8) {
  95. $time = dechex($time);
  96. } else {
  97. $time = bin2hex(BinaryUtil::fromBase($time, BinaryUtil::BASE10));
  98. }
  99. return substr_replace(sprintf('%012s-%04x-%04x-%04x%04x%04x',
  100. $time,
  101. 0x7000 | (self::$rand[1] << 2) | (self::$rand[2] >> 14),
  102. 0x8000 | (self::$rand[2] & 0x3FFF),
  103. self::$rand[3],
  104. self::$rand[4],
  105. self::$rand[5],
  106. ), '-', 8, 0);
  107. }
  108. }