Chris@0
|
1 <?php
|
Chris@0
|
2
|
Chris@0
|
3 namespace Drupal\Component\Uuid;
|
Chris@0
|
4
|
Chris@0
|
5 use Drupal\Component\Utility\Crypt;
|
Chris@0
|
6
|
Chris@0
|
7 /**
|
Chris@0
|
8 * Generates a UUID v4 (RFC 4122 section 4.4) using PHP code.
|
Chris@0
|
9 *
|
Chris@0
|
10 * @see http://www.rfc-editor.org/rfc/rfc4122.txt
|
Chris@0
|
11 * @see http://www.rfc-editor.org/errata_search.php?rfc=4122&eid=3546
|
Chris@0
|
12 */
|
Chris@0
|
13 class Php implements UuidInterface {
|
Chris@0
|
14
|
Chris@0
|
15 /**
|
Chris@0
|
16 * {@inheritdoc}
|
Chris@0
|
17 */
|
Chris@0
|
18 public function generate() {
|
Chris@0
|
19 // Obtain a random string of 32 hex characters.
|
Chris@0
|
20 $hex = bin2hex(Crypt::randomBytes(16));
|
Chris@0
|
21
|
Chris@0
|
22 // The variable names $time_low, $time_mid, $time_hi_and_version,
|
Chris@0
|
23 // $clock_seq_hi_and_reserved, $clock_seq_low, and $node correlate to
|
Chris@0
|
24 // the fields defined in RFC 4122 section 4.1.2.
|
Chris@0
|
25 //
|
Chris@0
|
26 // Use characters 0-11 to generate 32-bit $time_low and 16-bit $time_mid.
|
Chris@0
|
27 $time_low = substr($hex, 0, 8);
|
Chris@0
|
28 $time_mid = substr($hex, 8, 4);
|
Chris@0
|
29
|
Chris@0
|
30 // Use characters 12-15 to generate 16-bit $time_hi_and_version.
|
Chris@0
|
31 // The 4 most significant bits are the version number (0100 == 0x4).
|
Chris@0
|
32 // We simply skip character 12 from $hex, and concatenate the strings.
|
Chris@0
|
33 $time_hi_and_version = '4' . substr($hex, 13, 3);
|
Chris@0
|
34
|
Chris@0
|
35 // Use characters 16-17 to generate 8-bit $clock_seq_hi_and_reserved.
|
Chris@0
|
36 // The 2 most significant bits are set to one and zero respectively.
|
Chris@0
|
37 $clock_seq_hi_and_reserved = base_convert(substr($hex, 16, 2), 16, 10);
|
Chris@0
|
38 $clock_seq_hi_and_reserved &= 0b00111111;
|
Chris@0
|
39 $clock_seq_hi_and_reserved |= 0b10000000;
|
Chris@0
|
40
|
Chris@0
|
41 // Use characters 18-19 to generate 8-bit $clock_seq_low.
|
Chris@0
|
42 $clock_seq_low = substr($hex, 18, 2);
|
Chris@0
|
43 // Use characters 20-31 to generate 48-bit $node.
|
Chris@0
|
44 $node = substr($hex, 20);
|
Chris@0
|
45
|
Chris@0
|
46 // Re-combine as a UUID. $clock_seq_hi_and_reserved is still an integer.
|
Chris@0
|
47 $uuid = sprintf('%s-%s-%s-%02x%s-%s',
|
Chris@0
|
48 $time_low, $time_mid, $time_hi_and_version,
|
Chris@0
|
49 $clock_seq_hi_and_reserved, $clock_seq_low,
|
Chris@0
|
50 $node
|
Chris@0
|
51 );
|
Chris@0
|
52
|
Chris@0
|
53 return $uuid;
|
Chris@0
|
54 }
|
Chris@0
|
55
|
Chris@0
|
56 }
|