-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUuid.php
More file actions
472 lines (419 loc) · 11.7 KB
/
Copy pathUuid.php
File metadata and controls
472 lines (419 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
<?php
namespace Lambda\Dataform;
use Exception;
/**
* Class Uuid.
*
* @property string $bytes
* @property string $hex
* @property string $node
* @property string $string
* @property string $uuid_ordered
* @property string $time
* @property string $urn
* @property string $variant
* @property string $version
*/
class Uuid
{
const MD5 = 3;
const SHA1 = 5;
/**
* 00001111 Clears all bits of version byte with AND.
*
* @var int
*/
const CLEAR_VER = 15;
/**
* 00111111 Clears all relevant bits of variant byte with AND.
*
* @var int
*/
const CLEAR_VAR = 63;
/**
* 11100000 Variant reserved for future use.
*
* @var int
*/
const VAR_RES = 224;
/**
* 11000000 Microsoft UUID variant.
*
* @var int
*/
const VAR_MS = 192;
/**
* 10000000 The RFC 4122 variant (this variant).
*
* @var int
*/
const VAR_RFC = 128;
/**
* 00000000 The NCS compatibility variant.
*
* @var int
*/
const VAR_NCS = 0;
/**
* 00010000.
*
* @var int
*/
const VERSION_1 = 16;
/**
* 00110000.
*
* @var int
*/
const VERSION_3 = 48;
/**
* 01000000.
*
* @var int
*/
const VERSION_4 = 64;
/**
* 01010000.
*
* @var int
*/
const VERSION_5 = 80;
/**
* Time (in 100ns steps) between the start of the UTC and Unix epochs.
*
* @var int
*/
const INTERVAL = 0x01b21dd213814000;
/**
* @var string
*/
const NS_DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
/**
* @var string
*/
const NS_URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
/**
* @var string
*/
const NS_OID = '6ba7b812-9dad-11d1-80b4-00c04fd430c8';
/**
* @var string
*/
const NS_X500 = '6ba7b814-9dad-11d1-80b4-00c04fd430c8';
/**
* Regular expression for validation of UUID.
*/
const VALID_UUID_REGEX = '^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$';
/**
* @param string $uuid
*
* @throws Exception
*/
protected function __construct($uuid)
{
if (!empty($uuid) && strlen($uuid) !== 16) {
throw new Exception('Input must be a 128-bit integer.');
}
$this->bytes = $uuid;
// Optimize the most common use
$this->string = bin2hex(substr($uuid, 0, 4)).'-'.
bin2hex(substr($uuid, 4, 2)).'-'.
bin2hex(substr($uuid, 6, 2)).'-'.
bin2hex(substr($uuid, 8, 2)).'-'.
bin2hex(substr($uuid, 10, 6));
// Store UUID in an optimized way
$this->uuid_ordered = bin2hex(substr($uuid, 6, 2)).
bin2hex(substr($uuid, 4, 2)).
bin2hex(substr($uuid, 0, 4));
}
/**
* @param int $ver
* @param string $node
* @param string $ns
*
* @return Uuid
*
* @throws Exception
*/
public static function generate($ver = 1, $node = null, $ns = null)
{
/* Create a new UUID based on provided data. */
switch ((int) $ver) {
case 1:
return new static(static::mintTime($node));
case 2:
// Version 2 is not supported
throw new Exception('Version 2 is unsupported.');
case 3:
return new static(static::mintName(static::MD5, $node, $ns));
case 4:
return new static(static::mintRand());
case 5:
return new static(static::mintName(static::SHA1, $node, $ns));
default:
throw new Exception('Selected version is invalid or unsupported.');
}
}
/**
* Generates a Version 1 UUID.
* These are derived from the time at which they were generated.
*
* @param string $node
*
* @return string
*/
protected static function mintTime($node = null)
{
/** Get time since Gregorian calendar reform in 100ns intervals
* This is exceedingly difficult because of PHP's (and pack()'s)
* integer size limits.
* Note that this will never be more accurate than to the microsecond.
*/
$time = microtime(1) * 10000000 + static::INTERVAL;
// Convert to a string representation
$time = sprintf('%F', $time);
//strip decimal point
preg_match("/^\d+/", $time, $time);
// And now to a 64-bit binary representation
$time = base_convert($time[0], 10, 16);
$time = pack('H*', str_pad($time, 16, '0', STR_PAD_LEFT));
// Reorder bytes to their proper locations in the UUID
$uuid = $time[4].$time[5].$time[6].$time[7].$time[2].$time[3].$time[0].$time[1];
// Generate a random clock sequence
$uuid .= static::randomBytes(2);
// set variant
$uuid[8] = chr(ord($uuid[8]) & static::CLEAR_VAR | static::VAR_RFC);
// set version
$uuid[6] = chr(ord($uuid[6]) & static::CLEAR_VER | static::VERSION_1);
// Set the final 'node' parameter, a MAC address
if (!is_null($node)) {
$node = static::makeBin($node, 6);
}
// If no node was provided or if the node was invalid,
// generate a random MAC address and set the multicast bit
if (is_null($node)) {
$node = static::randomBytes(6);
$node[0] = pack('C', ord($node[0]) | 1);
}
$uuid .= $node;
return $uuid;
}
/**
* Randomness is returned as a string of bytes.
*
* @param $bytes
*
* @return string
*/
public static function randomBytes($bytes)
{
return random_bytes($bytes);
}
/**
* Insure that an input string is either binary or hexadecimal.
* Returns binary representation, or false on failure.
*
* @param string $str
* @param int $len
*
* @return string|null
*/
protected static function makeBin($str, $len)
{
if ($str instanceof self) {
return $str->bytes;
}
if (strlen($str) === $len) {
return $str;
} else {
// strip URN scheme and namespace
$str = preg_replace('/^urn:uuid:/is', '', $str);
}
// strip non-hex characters
$str = preg_replace('/[^a-f0-9]/is', '', $str);
if (strlen($str) !== ($len * 2)) {
return null;
} else {
return pack('H*', $str);
}
}
/**
* Generates a Version 3 or Version 5 UUID.
* These are derived from a hash of a name and its namespace, in binary form.
*
* @param string $ver
* @param string $node
* @param string $ns
*
* @return string
*
* @throws Exception
*/
protected static function mintName($ver, $node, $ns)
{
if (empty($node)) {
throw new Exception('A name-string is required for Version 3 or 5 UUIDs.');
}
// if the namespace UUID isn't binary, make it so
$ns = static::makeBin($ns, 16);
if (is_null($ns)) {
throw new Exception('A binary namespace is required for Version 3 or 5 UUIDs.');
}
$version = null;
$uuid = null;
switch ($ver) {
case static::MD5:
$version = static::VERSION_3;
$uuid = md5($ns.$node, 1);
break;
case static::SHA1:
$version = static::VERSION_5;
$uuid = substr(sha1($ns.$node, 1), 0, 16);
break;
default:
// no default really required here
}
// set variant
$uuid[8] = chr(ord($uuid[8]) & static::CLEAR_VAR | static::VAR_RFC);
// set version
$uuid[6] = chr(ord($uuid[6]) & static::CLEAR_VER | $version);
return $uuid;
}
/**
* Generate a Version 4 UUID.
* These are derived solely from random numbers.
* generate random fields.
*
* @return string
*/
protected static function mintRand()
{
$uuid = static::randomBytes(16);
// set variant
$uuid[8] = chr(ord($uuid[8]) & static::CLEAR_VAR | static::VAR_RFC);
// set version
$uuid[6] = chr(ord($uuid[6]) & static::CLEAR_VER | static::VERSION_4);
return $uuid;
}
/**
* Import an existing UUID.
*
* @param string $uuid
*
* @return Uuid
*/
public static function import($uuid)
{
return new static(static::makeBin($uuid, 16));
}
/**
* Compares the binary representations of two UUIDs.
* The comparison will return true if they are bit-exact,
* or if neither is valid.
*
* @param string $a
* @param string $b
*
* @return string|string
*/
public static function compare($a, $b)
{
if (static::makeBin($a, 16) == static::makeBin($b, 16)) {
return true;
} else {
return false;
}
}
/**
* @param string $var
*
* @return string|string|number|number|number|number|number|null|number|null|null
*/
public function __get($var)
{
switch ($var) {
case 'bytes':
return $this->bytes;
break;
case 'hex':
return bin2hex($this->bytes);
break;
case 'node':
if (ord($this->bytes[6]) >> 4 == 1) {
return bin2hex(substr($this->bytes, 10));
} else {
return null;
}
break;
case 'string':
return $this->__toString();
break;
case 'uuid_ordered':
return $this->__toUuidOrdered();
break;
case 'time':
if (ord($this->bytes[6]) >> 4 == 1) {
// Restore contiguous big-endian byte order
$time = bin2hex($this->bytes[6].$this->bytes[7].$this->bytes[4].$this->bytes[5].
$this->bytes[0].$this->bytes[1].$this->bytes[2].$this->bytes[3]);
// Clear version flag
$time[0] = '0';
// Do some reverse arithmetic to get a Unix timestamp
return (hexdec($time) - static::INTERVAL) / 10000000;
} else {
return null;
}
break;
case 'urn':
return 'urn:uuid:'.$this->__toString();
break;
case 'variant':
$byte = ord($this->bytes[8]);
if ($byte >= static::VAR_RES) {
return 3;
} elseif ($byte >= static::VAR_MS) {
return 2;
} elseif ($byte >= static::VAR_RFC) {
return 1;
} else {
return 0;
}
break;
case 'version':
return ord($this->bytes[6]) >> 4;
break;
default:
return null;
break;
}
}
/**
* Return the UUID.
*
* @return string
*/
public function __toString()
{
return $this->string;
}
/**
* Return the UUID ORDERED.
*
* @return uuid ordered
*/
public function __toUuidOrdered()
{
return $this->uuid_ordered;
}
/**
* Import and validate an UUID.
*
* @param Uuid|string $uuid
*
* @return bool
*/
public static function validate($uuid)
{
return (bool) preg_match('~'.static::VALID_UUID_REGEX.'~', static::import($uuid)->string);
}
}