Skip to content

Commit 9f1c51b

Browse files
authored
Merge pull request #356 from thekid/feature/uuid-v7
Implement UUID v7 - time-ordered UUIDs
2 parents 0e0c048 + 93e8fcf commit 9f1c51b

2 files changed

Lines changed: 37 additions & 0 deletions

File tree

src/main/php/util/UUID.class.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,33 @@ public static function randomUUID() {
228228
]);
229229
}
230230

231+
/**
232+
* Create a version 7 UUID based upon the UNIX epoch in milliseconds and
233+
* pseudorandom bits
234+
*
235+
* @param ?int $ms
236+
* @return self
237+
*/
238+
public static function timeOrderedUUID($ms= null) {
239+
$t= (int)($ms ?? microtime(true) * 1000);
240+
241+
return new self([
242+
7,
243+
($t >> 16) & 0xffffffff,
244+
$t & 0xffff,
245+
random_int(0, 0x0fff),
246+
random_int(0, 0x3fff) | 0x8000,
247+
[
248+
random_int(0, 0xff),
249+
random_int(0, 0xff),
250+
random_int(0, 0xff),
251+
random_int(0, 0xff),
252+
random_int(0, 0xff),
253+
random_int(0, 0xff),
254+
]
255+
]);
256+
}
257+
231258
/**
232259
* Returns version
233260
*

src/test/php/util/unittest/UUIDTest.class.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,16 @@ public function twoRandomUUIDsNotEqual() {
147147
Assert::notEquals(UUID::randomUUID(), UUID::randomUUID());
148148
}
149149

150+
#[Test]
151+
public function timeOrderedUUID() {
152+
Assert::equals(7, UUID::timeOrderedUUID()->version());
153+
}
154+
155+
#[Test]
156+
public function timeOrderedUUIDPrefix() {
157+
Assert::matches('/^019bf452-f817/', UUID::timeOrderedUUID(1769330636823)->hashCode());
158+
}
159+
150160
#[Test]
151161
public function md5UUID() {
152162
Assert::equals(3, UUID::md5UUID(UUID::$NS_DNS, 'example.com')->version());

0 commit comments

Comments
 (0)