- Change multiple field matching to enum
- Implement auto-generated IDs

Reviewed-on: #2
This commit was merged in pull request #2.
This commit is contained in:
2024-06-11 11:07:56 +00:00
parent 1f1f06679f
commit 330e272187
26 changed files with 617 additions and 73 deletions

51
src/AutoId.php Normal file
View File

@@ -0,0 +1,51 @@
<?php 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
*
* @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(): string
{
return bin2hex(random_bytes(Configuration::$idStringLength / 2));
}
}