59 lines
1.7 KiB
PHP
59 lines
1.7 KiB
PHP
<?php
|
|
/**
|
|
* @author Daniel J. Summers <daniel@bitbadger.solutions>
|
|
* @license MIT
|
|
*/
|
|
|
|
declare(strict_types=1);
|
|
|
|
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
|
|
*
|
|
* @param int|null $length The length of string to generate (optional; defaults to configured ID string length)
|
|
* @return string A string filled with the hexadecimal representation of random bytes
|
|
* @throws RandomException If an appropriate source of randomness cannot be found
|
|
*/
|
|
public static function generateRandom(?int $length = null): string
|
|
{
|
|
return bin2hex(random_bytes(($length ?? Configuration::$idStringLength) / 2));
|
|
}
|
|
}
|