From 47ffeee9e16fb51ab8402014172adf4f96d7a430 Mon Sep 17 00:00:00 2001 From: esyede Date: Thu, 26 Sep 2024 00:18:31 +0700 Subject: [PATCH] System: add Str::uuid7() --- system/str.php | 23 +++++++++++++++++++++++ tests/cases/str.test.php | 2 ++ 2 files changed, 25 insertions(+) diff --git a/system/str.php b/system/str.php index 7df0efbe..52180351 100644 --- a/system/str.php +++ b/system/str.php @@ -544,6 +544,29 @@ public static function uuid() return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex(static::bytes(16)), 4)); } + /** + * Buat string UUID (versi 7). + * (Universally Unique Identifier versi 7). + * + * @return string + */ + public static function uuid7() + { + $ts = intval(microtime(true) * 1000); + return sprintf( + '%02x%02x%02x%02x-%02x%02x-%04x-%04x-%012x', + ($ts >> 40) & 0xFF, + ($ts >> 32) & 0xFF, + ($ts >> 24) & 0xFF, + ($ts >> 16) & 0xFF, + ($ts >> 8) & 0xFF, + $ts & 0xFF, + static::integers(0, 0x0FFF) | 0x7000, + static::integers(0, 0x3FFF) | 0x8000, + static::integers(0, 0xFFFFFFFFFFFF), + ); + } + /** * Buat string ULID. * (Universally Unique Lexicographically Sortable Identifier). diff --git a/tests/cases/str.test.php b/tests/cases/str.test.php index e894ea33..12d5f4e1 100644 --- a/tests/cases/str.test.php +++ b/tests/cases/str.test.php @@ -304,6 +304,8 @@ public function testUuid() $this->assertTrue((bool) preg_match('/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/Di', $uuid)); } + + public function testUlid() { $this->assertTrue((bool) preg_match('/[0-9][A-Z]/', Str::ulid()));