2024-07-21 01:47:21 +00:00
|
|
|
<?php
|
|
|
|
/**
|
|
|
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
|
|
|
* @license MIT
|
|
|
|
*/
|
|
|
|
|
|
|
|
declare(strict_types=1);
|
2024-06-11 11:07:56 +00:00
|
|
|
|
|
|
|
namespace BitBadger\PDODocument;
|
|
|
|
|
|
|
|
use Random\RandomException;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* How automatic ID generation should be performed
|
|
|
|
*/
|
|
|
|
enum AutoId
|
|
|
|
{
|
|
|
|
/** Do not automatically generate IDs */
|
|
|
|
case None;
|
|
|
|
|
|
|
|
/** New documents with a 0 ID should receive max ID plus one */
|
|
|
|
case Number;
|
|
|
|
|
|
|
|
/** New documents with a blank ID should receive a v4 UUID (Universally Unique Identifier) */
|
|
|
|
case UUID;
|
|
|
|
|
|
|
|
/** New documents with a blank ID should receive a random string (set `Configuration::$idStringLength`) */
|
|
|
|
case RandomString;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Generate a v4 UUID
|
|
|
|
*
|
|
|
|
* @return string The v4 UUID
|
|
|
|
* @throws RandomException If an appropriate source of randomness cannot be found
|
|
|
|
*/
|
|
|
|
public static function generateUUID(): string
|
|
|
|
{
|
|
|
|
// hat tip: https://stackoverflow.com/a/15875555/276707
|
|
|
|
$bytes = random_bytes(16);
|
|
|
|
|
|
|
|
$bytes[6] = chr(ord($bytes[6]) & 0x0f | 0x40); // set version to 0100
|
|
|
|
$bytes[8] = chr(ord($bytes[8]) & 0x3f | 0x80); // set bits 6-7 to 10
|
|
|
|
|
|
|
|
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4));
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Generate a random string ID
|
|
|
|
*
|
2024-06-21 13:46:41 +00:00
|
|
|
* @param int|null $length The length of string to generate (optional; defaults to configured ID string length)
|
2024-06-11 11:07:56 +00:00
|
|
|
* @return string A string filled with the hexadecimal representation of random bytes
|
|
|
|
* @throws RandomException If an appropriate source of randomness cannot be found
|
|
|
|
*/
|
2024-06-21 13:46:41 +00:00
|
|
|
public static function generateRandom(?int $length = null): string
|
2024-06-11 11:07:56 +00:00
|
|
|
{
|
2024-06-21 13:46:41 +00:00
|
|
|
return bin2hex(random_bytes(($length ?? Configuration::$idStringLength) / 2));
|
2024-06-11 11:07:56 +00:00
|
|
|
}
|
|
|
|
}
|