From 93e8fcf01be5d4cbabf02c3f9a19247148076b99 Mon Sep 17 00:00:00 2001 From: Timm Friebe Date: Sat, 31 Jan 2026 11:04:46 +0100 Subject: [PATCH] Implement UUID v7 - time-ordered UUIDs --- src/main/php/util/UUID.class.php | 27 +++++++++++++++++++ src/test/php/util/unittest/UUIDTest.class.php | 10 +++++++ 2 files changed, 37 insertions(+) diff --git a/src/main/php/util/UUID.class.php b/src/main/php/util/UUID.class.php index e8bdce5d3..b0708074c 100755 --- a/src/main/php/util/UUID.class.php +++ b/src/main/php/util/UUID.class.php @@ -228,6 +228,33 @@ public static function randomUUID() { ]); } + /** + * Create a version 7 UUID based upon the UNIX epoch in milliseconds and + * pseudorandom bits + * + * @param ?int $ms + * @return self + */ + public static function timeOrderedUUID($ms= null) { + $t= (int)($ms ?? microtime(true) * 1000); + + return new self([ + 7, + ($t >> 16) & 0xffffffff, + $t & 0xffff, + random_int(0, 0x0fff), + random_int(0, 0x3fff) | 0x8000, + [ + random_int(0, 0xff), + random_int(0, 0xff), + random_int(0, 0xff), + random_int(0, 0xff), + random_int(0, 0xff), + random_int(0, 0xff), + ] + ]); + } + /** * Returns version * diff --git a/src/test/php/util/unittest/UUIDTest.class.php b/src/test/php/util/unittest/UUIDTest.class.php index 606cb8470..a511116d6 100755 --- a/src/test/php/util/unittest/UUIDTest.class.php +++ b/src/test/php/util/unittest/UUIDTest.class.php @@ -147,6 +147,16 @@ public function twoRandomUUIDsNotEqual() { Assert::notEquals(UUID::randomUUID(), UUID::randomUUID()); } + #[Test] + public function timeOrderedUUID() { + Assert::equals(7, UUID::timeOrderedUUID()->version()); + } + + #[Test] + public function timeOrderedUUIDPrefix() { + Assert::matches('/^019bf452-f817/', UUID::timeOrderedUUID(1769330636823)->hashCode()); + } + #[Test] public function md5UUID() { Assert::equals(3, UUID::md5UUID(UUID::$NS_DNS, 'example.com')->version());