-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuuid4.php
64 lines (52 loc) · 1.33 KB
/
uuid4.php
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
<?php
namespace Antikirra;
use InvalidArgumentException;
if (version_compare(PHP_VERSION, '7.0.0', '<') || !function_exists('random_bytes')) {
/**
* @param int $length
* @return string
*/
function random_bytes($length)
{
static $prev;
$bytes = '';
while (strlen($bytes) < $length) {
list($a, $b) = tsids(2);
$i = hash('md4', implode("#", [$prev, mt_rand(), $a, mt_rand(), $b]), true);
$prev = $i;
$bytes .= $i;
}
if (strlen($bytes) > $length) {
$bytes = substr($bytes, 0, $length);
}
return $bytes;
}
}
if (!function_exists('Antikirra\\uuid4')) {
/**
* @return string
*/
function uuid4()
{
$hex = bin2hex(random_bytes(18));
$hex[8] = $hex[13] = $hex[18] = $hex[23] = '-';
$hex[14] = '4';
return $hex;
}
}
if (!function_exists('Antikirra\\uuid4_validate')) {
/**
* @param string $uuid4
* @return bool
*/
function uuid4_validate($uuid4)
{
if (!is_string($uuid4)) {
throw new InvalidArgumentException();
}
if (strlen($uuid4) !== 36) {
return false;
}
return (bool)preg_match('~^[a-f\d]{8}-[a-f\d]{4}-4[a-f\d]{3}-[a-f\d]{4}-[a-f\d]{12}$~', $uuid4);
}
}