Files
server/shared/lib/Utile/UUID.php
2026-02-10 18:46:11 -05:00

55 lines
1.1 KiB
PHP

<?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
);
}
}