Initial Version
This commit is contained in:
54
shared/lib/Utile/UUID.php
Normal file
54
shared/lib/Utile/UUID.php
Normal file
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* SPDX-FileCopyrightText: Sebastian Krupinski <krupinski01@gmail.com>
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
namespace KTXF\Utile;
|
||||
|
||||
/**
|
||||
* UUID Generator Utility Class
|
||||
*
|
||||
* Generates RFC 4122 compliant UUIDs (version 4 - random)
|
||||
*/
|
||||
class UUID {
|
||||
|
||||
/**
|
||||
* Generate a random UUID v4
|
||||
*
|
||||
* @return string UUID in format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
|
||||
*/
|
||||
public static function v4(): string {
|
||||
// Generate 16 random bytes
|
||||
$bytes = random_bytes(16);
|
||||
|
||||
// Set version to 4 (random)
|
||||
$bytes[6] = chr((ord($bytes[6]) & 0x0f) | 0x40);
|
||||
|
||||
// Set variant to RFC 4122
|
||||
$bytes[8] = chr((ord($bytes[8]) & 0x3f) | 0x80);
|
||||
|
||||
// Format as UUID string
|
||||
return vsprintf(
|
||||
'%s%s-%s-%s-%s-%s%s%s',
|
||||
str_split(bin2hex($bytes), 4)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a UUID string
|
||||
*
|
||||
* @param string $uuid UUID to validate
|
||||
* @return bool True if valid UUID format
|
||||
*/
|
||||
public static function isValid(string $uuid): bool {
|
||||
return (bool)preg_match(
|
||||
'/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i',
|
||||
$uuid
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user