UuidV1.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 v1 UUID contains a 60-bit timestamp and 62 extra unique bits.
  13. *
  14. * @author Grégoire Pineau <lyrixx@lyrixx.info>
  15. */
  16. class UuidV1 extends Uuid implements TimeBasedUidInterface
  17. {
  18. protected const TYPE = 1;
  19. private static string $clockSeq;
  20. public function __construct(?string $uuid = null)
  21. {
  22. if (null === $uuid) {
  23. $this->uid = strtolower(uuid_create(static::TYPE));
  24. } else {
  25. parent::__construct($uuid, true);
  26. }
  27. }
  28. public function getDateTime(): \DateTimeImmutable
  29. {
  30. return BinaryUtil::hexToDateTime('0'.substr($this->uid, 15, 3).substr($this->uid, 9, 4).substr($this->uid, 0, 8));
  31. }
  32. public function getNode(): string
  33. {
  34. return uuid_mac($this->uid);
  35. }
  36. public static function generate(?\DateTimeInterface $time = null, ?Uuid $node = null): string
  37. {
  38. $uuid = !$time || !$node ? uuid_create(static::TYPE) : parent::NIL;
  39. if ($time) {
  40. if ($node) {
  41. // use clock_seq from the node
  42. $seq = substr($node->uid, 19, 4);
  43. } elseif (!$seq = self::$clockSeq ?? '') {
  44. // generate a static random clock_seq to prevent any collisions with the real one
  45. $seq = substr($uuid, 19, 4);
  46. do {
  47. self::$clockSeq = \sprintf('%04x', random_int(0, 0x3FFF) | 0x8000);
  48. } while ($seq === self::$clockSeq);
  49. $seq = self::$clockSeq;
  50. }
  51. $time = BinaryUtil::dateTimeToHex($time);
  52. $uuid = substr($time, 8).'-'.substr($time, 4, 4).'-1'.substr($time, 1, 3).'-'.$seq.substr($uuid, 23);
  53. }
  54. if ($node) {
  55. $uuid = substr($uuid, 0, 24).substr($node->uid, 24);
  56. }
  57. return $uuid;
  58. }
  59. }