1 | <?php |
||
23 | final class UuidGenerator extends AbstractIdGenerator |
||
24 | { |
||
25 | /** |
||
26 | * A unique environment value to salt each UUID with. |
||
27 | * |
||
28 | * @var string |
||
29 | */ |
||
30 | protected $salt = null; |
||
31 | |||
32 | /** |
||
33 | * Used to set the salt that will be applied to each id |
||
34 | */ |
||
35 | public function setSalt(string $salt) : void |
||
36 | 6 | { |
|
37 | $this->salt = $salt; |
||
38 | 6 | } |
|
39 | 6 | ||
40 | /** |
||
41 | * Returns the current salt value |
||
42 | * |
||
43 | * @return string $salt The current salt |
||
44 | */ |
||
45 | public function getSalt() : string |
||
49 | |||
50 | 2 | /** |
|
51 | 2 | * Checks that a given string is a valid uuid. |
|
52 | */ |
||
53 | public function isValid(string $uuid) : bool |
||
58 | 1 | ||
59 | /** |
||
60 | 1 | * Generates a new UUID |
|
61 | * |
||
62 | * @param DocumentManager $dm Not used. |
||
63 | * @param object $document Not used. |
||
64 | * |
||
65 | * @return string UUID |
||
66 | 2 | * |
|
67 | * @throws Exception |
||
68 | 2 | */ |
|
69 | 2 | public function generate(DocumentManager $dm, object $document) |
|
70 | { |
||
71 | $uuid = $this->generateV4(); |
||
72 | return $this->generateV5($uuid, $this->salt ?: php_uname('n')); |
||
73 | } |
||
74 | |||
75 | /** |
||
76 | * Generates a v4 UUID |
||
77 | */ |
||
78 | public function generateV4() : string |
||
79 | { |
||
80 | return sprintf( |
||
81 | '%04x%04x%04x%04x%04x%04x%04x%04x', |
||
82 | 2 | // 32 bits for "time_low" |
|
83 | mt_rand(0, 0xffff), |
||
84 | 2 | mt_rand(0, 0xffff), |
|
85 | 2 | // 16 bits for "time_mid" |
|
86 | mt_rand(0, 0xffff), |
||
87 | // 16 bits for "time_hi_and_version", |
||
88 | // four most significant bits holds version number 4 |
||
89 | mt_rand(0, 0x0fff) | 0x4000, |
||
90 | // 16 bits, 8 bits for "clk_seq_hi_res", |
||
91 | 4 | // 8 bits for "clk_seq_low", |
|
92 | // two most significant bits holds zero and one for variant DCE1.1 |
||
93 | 4 | mt_rand(0, 0x3fff) | 0x8000, |
|
94 | 4 | // 48 bits for "node" |
|
95 | mt_rand(0, 0xffff), |
||
96 | 4 | mt_rand(0, 0xffff), |
|
97 | 4 | mt_rand(0, 0xffff) |
|
98 | ); |
||
99 | 4 | } |
|
100 | |||
101 | /** |
||
102 | 4 | * Generates a v5 UUID |
|
103 | * |
||
104 | * @throws Exception When the provided namespace is invalid. |
||
105 | */ |
||
106 | 4 | public function generateV5(string $namespace, string $salt) : string |
|
143 | } |
||
144 |