Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/main/php/util/UUID.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*
Expand Down
10 changes: 10 additions & 0 deletions src/test/php/util/unittest/UUIDTest.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down