1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
4
|
|
|
|
5
|
|
|
namespace Sop\JWX\Util; |
6
|
|
|
|
7
|
|
|
/* |
8
|
|
|
Layout and Byte Order |
9
|
|
|
http://tools.ietf.org/search/rfc4122#section-4.1.2 |
10
|
|
|
|
11
|
|
|
0 1 2 3 |
12
|
|
|
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 |
13
|
|
|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |
14
|
|
|
| time_low | |
15
|
|
|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |
16
|
|
|
| time_mid | time_hi_and_version | |
17
|
|
|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |
18
|
|
|
|clk_seq_hi_res | clk_seq_low | node (0-1) | |
19
|
|
|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |
20
|
|
|
| node (2-5) | |
21
|
|
|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |
22
|
|
|
*/ |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* UUID version 4. |
26
|
|
|
* |
27
|
|
|
* @see http://tools.ietf.org/search/rfc4122#section-4.4 |
28
|
|
|
*/ |
29
|
|
|
class UUIDv4 |
30
|
|
|
{ |
31
|
|
|
/** |
32
|
|
|
* UUID. |
33
|
|
|
* |
34
|
|
|
* @var string |
35
|
|
|
*/ |
36
|
|
|
protected $_uuid; |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* Constructor. |
40
|
|
|
* |
41
|
|
|
* @param string $uuid UUIDv4 in canonical hexadecimal format |
42
|
|
|
*/ |
43
|
2 |
|
public function __construct(string $uuid) |
44
|
|
|
{ |
45
|
|
|
// @todo Check that UUID is version 4 |
46
|
2 |
|
$this->_uuid = $uuid; |
47
|
2 |
|
} |
48
|
|
|
|
49
|
1 |
|
public function __toString(): string |
50
|
|
|
{ |
51
|
1 |
|
return $this->canonical(); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Create new random UUIDv4. |
56
|
|
|
*/ |
57
|
1 |
|
public static function createRandom(): self |
58
|
|
|
{ |
59
|
|
|
/* |
60
|
|
|
1. Set the two most significant bits (bits 6 and 7) of |
61
|
|
|
the clock_seq_hi_and_reserved to zero and one, respectively. |
62
|
|
|
|
63
|
|
|
2. Set the four most significant bits (bits 12 through 15) of |
64
|
|
|
the time_hi_and_version field to the 4-bit version number |
65
|
|
|
from Section 4.1.3. |
66
|
|
|
|
67
|
|
|
3. Set all the other bits to randomly (or pseudo-randomly) |
68
|
|
|
chosen values. |
69
|
|
|
*/ |
70
|
1 |
|
$uuid = sprintf('%04x%04x-%04x-%04x-%02x%02x-%04x%04x%04x', |
71
|
|
|
// time_low |
72
|
1 |
|
mt_rand(0, 0xffff), mt_rand(0, 0xffff), |
73
|
|
|
// time_mid |
74
|
1 |
|
mt_rand(0, 0xffff), |
75
|
|
|
// time_hi_and_version |
76
|
1 |
|
mt_rand(0, 0x0fff) | 0x4000, |
77
|
|
|
// clk_seq_hi_res |
78
|
1 |
|
mt_rand(0, 0x3f) | 0x80, |
79
|
|
|
// clk_seq_low |
80
|
1 |
|
mt_rand(0, 0xff), |
81
|
|
|
// node |
82
|
1 |
|
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)); |
83
|
1 |
|
return new self($uuid); |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
/** |
87
|
|
|
* Get UUIDv4 in canonical form. |
88
|
|
|
*/ |
89
|
2 |
|
public function canonical(): string |
90
|
|
|
{ |
91
|
2 |
|
return $this->_uuid; |
92
|
|
|
} |
93
|
|
|
} |
94
|
|
|
|