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