src/UUID/functions.php source

1 <?php
2
3 namespace mini;
4
5 use mini\UUID\FactoryInterface;
6
7 // Register UUID factory service
8 Mini::$mini->addService(FactoryInterface::class, Lifetime::Singleton, fn() => Mini::$mini->loadServiceConfig(FactoryInterface::class));
9
10 /**
11 * Generate a new UUID/GUID.
12 *
13 * By default, generates a UUID v7 (time-ordered + cryptographically random).
14 * Can be customized by providing a factory implementation at:
15 *
16 * `_config/mini/UUID/FactoryInterface.php`
17 *
18 * ## Example Usage
19 *
20 * ```php
21 * $id = uuid(); // "018c8f3a-2b4e-7a1c-9f23-4d5e6f7a8b9c"
22 * ```
23 *
24 * ## Custom Factory Example
25 *
26 * ```php
27 * // _config/mini/UUID/FactoryInterface.php
28 * return new class implements \mini\UUID\FactoryInterface {
29 * public function make(): string {
30 * // Custom UUID generation logic
31 * return '...';
32 * }
33 * };
34 * ```
35 *
36 * @return string A UUID string (default: v7 format)
37 */
38 function uuid(): string {
39 return Mini::$mini->get(FactoryInterface::class)->make();
40 }
41
42 /**
43 * Generate a UUID v4 (cryptographically random).
44 *
45 * UUID v4 provides 122 bits of cryptographic randomness with no temporal component.
46 * Use when you need maximum unpredictability or want to avoid timestamp leakage.
47 *
48 * ## Example Usage
49 *
50 * ```php
51 * $token = uuid4(); // "550e8400-e29b-41d4-a716-446655440000"
52 * ```
53 *
54 * ## Common Use Cases
55 *
56 * - API tokens and session identifiers
57 * - Password reset tokens
58 * - Shareable links (prevents enumeration)
59 * - Privacy-sensitive identifiers
60 *
61 * @return string A UUID v4 string
62 */
63 function uuid4(): string {
64 return (new UUID\UUID4Factory())->make();
65 }
66
67 /**
68 * Generate a UUID v7 (time-ordered + cryptographically random).
69 *
70 * UUID v7 combines Unix timestamp (milliseconds) with cryptographic randomness,
71 * providing natural chronological ordering and better database index performance.
72 *
73 * ## Example Usage
74 *
75 * ```php
76 * $id = uuid7(); // "018c8f3a-2b4e-7a1c-9f23-4d5e6f7a8b9c"
77 * ```
78 *
79 * ## Common Use Cases
80 *
81 * - Database primary keys (better B-tree performance)
82 * - Sortable identifiers
83 * - Time-range queries
84 * - High-volume write operations
85 *
86 * Note: This is the same as uuid() by default, but calling uuid7() explicitly
87 * ensures you get v7 even if the default factory is customized.
88 *
89 * @return string A UUID v7 string
90 */
91 function uuid7(): string {
92 return (new UUID\UUID7Factory())->make();
93 }
94