1: <?php
2:
3: namespace nightmare;
4:
5: class uuid
6: {
7: public static function v4()
8: {
9: $b = random_bytes(16);
10: $b[6] = chr(ord($b[6]) & 0x0f | 0x40);
11: $b[8] = chr(ord($b[8]) & 0x3f | 0x80);
12:
13: $hex = bin2hex($b);
14:
15: return sprintf(
16: '%s%s-%s-%s-%s-%s%s%s',
17: substr($hex, 0, 4),
18: substr($hex, 4, 4),
19: substr($hex, 8, 4),
20: substr($hex, 12, 4),
21: substr($hex, 16, 4),
22: substr($hex, 20, 4),
23: substr($hex, 24, 4),
24: substr($hex, 28, 4)
25: );
26: }
27:
28: // uuidv7 see https://www.rfc-editor.org/rfc/rfc9562#name-uuid-version-7
29: public static function v7()
30: {
31: // 1) Lấy timestamp mili-giây từ Unix Epoch (UTC)
32: $unix_ms = (int) (microtime(true) * 1000);
33:
34: // 2) 48-bit timestamp big-endian -> 6 byte
35: // N = 32-bit big-endian, n = 16-bit big-endian
36: $time_bytes = pack('Nn', $unix_ms >> 16, $unix_ms & 0xFFFF);
37:
38: // 3) 10 byte ngẫu nhiên (crypto-safe)
39: $rand_bytes = random_bytes(10);
40:
41: // 4) Ghép thành 16 byte
42: $bytes = $time_bytes . $rand_bytes;
43:
44: // 5) Set version 7 (0111) vào high nibble của byte thứ 7 (index 6)
45: $bytes[6] = chr((ord($bytes[6]) & 0x0F) | 0x70);
46:
47: // 6) Set variant RFC 4122 -> 10xxxxxx vào byte thứ 9 (index 8)
48: $bytes[8] = chr((ord($bytes[8]) & 0x3F) | 0x80);
49:
50: // 7) Chuyển sang dạng string 8-4-4-4-12
51: $hex = bin2hex($bytes);
52:
53: return sprintf(
54: '%s-%s-%s-%s-%s',
55: substr($hex, 0, 8),
56: substr($hex, 8, 4),
57: substr($hex, 12, 4),
58: substr($hex, 16, 4),
59: substr($hex, 20),
60: );
61: }
62: }
63: