mirror of
https://github.com/Lastorder-DC/rhymix.git
synced 2026-05-22 05:15:29 +09:00
Support both UUIDv4 and UUIDv7 in Security::getRandomUUID()
This commit is contained in:
parent
c01ba1d3cf
commit
f8ed6da4ed
2 changed files with 32 additions and 4 deletions
|
|
@ -252,13 +252,31 @@ class Security
|
||||||
/**
|
/**
|
||||||
* Generate a random UUID.
|
* Generate a random UUID.
|
||||||
*
|
*
|
||||||
|
* The code for UUIDv4 is based on https://stackoverflow.com/a/15875555/481206
|
||||||
|
*
|
||||||
|
* @param int $version (4 or 7)
|
||||||
* @return string
|
* @return string
|
||||||
*/
|
*/
|
||||||
public static function getRandomUUID(): string
|
public static function getRandomUUID(int $version = 4): string
|
||||||
{
|
{
|
||||||
$randpool = self::getRandom(16, 'binary');
|
if ($version === 4)
|
||||||
$randpool[6] = chr(ord($randpool[6]) & 0x0f | 0x40);
|
{
|
||||||
$randpool[8] = chr(ord($randpool[8]) & 0x3f | 0x80);
|
$randpool = self::getRandom(16, 'binary');
|
||||||
|
$randpool[6] = chr(ord($randpool[6]) & 0x0f | 0x40);
|
||||||
|
$randpool[8] = chr(ord($randpool[8]) & 0x3f | 0x80);
|
||||||
|
}
|
||||||
|
elseif ($version === 7)
|
||||||
|
{
|
||||||
|
$timestamp = microtime(false);
|
||||||
|
$timestamp = substr(pack('J', (intval(substr($timestamp, -10), 10) * 1000) + intval(substr($timestamp, 2, 3), 10)), -6);
|
||||||
|
$randpool = $timestamp . self::getRandom(10, 'binary');
|
||||||
|
$randpool[6] = chr(ord($randpool[6]) & 0x0f | 0x70);
|
||||||
|
$randpool[8] = chr(ord($randpool[8]) & 0x3f | 0x80);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
throw new Exception('Invalid UUID version: ' . $version);
|
||||||
|
}
|
||||||
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($randpool), 4));
|
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($randpool), 4));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -83,6 +83,16 @@ class SecurityTest extends \Codeception\TestCase\Test
|
||||||
{
|
{
|
||||||
$this->assertRegExp($regex, Rhymix\Framework\Security::getRandomUUID());
|
$this->assertRegExp($regex, Rhymix\Framework\Security::getRandomUUID());
|
||||||
}
|
}
|
||||||
|
for ($i = 0; $i < 10; $i++)
|
||||||
|
{
|
||||||
|
$this->assertRegExp($regex, Rhymix\Framework\Security::getRandomUUID(4));
|
||||||
|
}
|
||||||
|
|
||||||
|
$regex = '/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/';
|
||||||
|
for ($i = 0; $i < 10; $i++)
|
||||||
|
{
|
||||||
|
$this->assertRegExp($regex, Rhymix\Framework\Security::getRandomUUID(7));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public function testCompareStrings()
|
public function testCompareStrings()
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue