Class that generates and validates UUIDs.
Protected constructor since this is a static class.
NULL
protected function __construct()
{
// Nothing here
}
Checks if a UUID is valid.
| Type | Description |
|---|---|
| string | The UUID to validate |
boolean
public static function valid($str)
{
return (bool) preg_match('/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i', $str);
}
Converts UUID to binary.
| Type | Description |
|---|---|
| string | UUID |
string
protected static function toBin($namespace)
{
if(!static::valid($namespace))
{
throw new InvalidArgumentException(vsprintf("%s(): Provided namespace is not a valid UUID.", array(__METHOD__)));
}
// Get hexadecimal components of namespace
$nhex = str_replace(array('-','{','}'), '', $namespace);
// Binary Value
$nstr = '';
// Convert Namespace UUID to bits
for($i = 0; $i < strlen($nhex); $i+=2)
{
$nstr .= chr(hexdec($nhex[$i].$nhex[$i+1]));
}
return $nstr;
}
Returns a V3 UUID.
| Type | Description |
|---|---|
| string | Namespace |
| string | Name |
string
public static function v3($namespace, $name)
{
// Calculate hash value
$hash = md5(self::toBin($namespace) . $name);
return sprintf
(
'%08s-%04s-%04x-%04x-%12s',
// 32 bits for "time_low"
substr($hash, 0, 8),
// 16 bits for "time_mid"
substr($hash, 8, 4),
// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 3
(hexdec(substr($hash, 12, 4)) & 0x0fff) | 0x3000,
// 16 bits, 8 bits for "clk_seq_hi_res",
// 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
(hexdec(substr($hash, 16, 4)) & 0x3fff) | 0x8000,
// 48 bits for "node"
substr($hash, 20, 12)
);
}
Returns a V4 UUID.
string
public static function v4()
{
return sprintf
(
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
// 32 bits for "time_low"
mt_rand(0, 65535),
mt_rand(0, 65535),
// 16 bits for "time_mid"
mt_rand(0, 65535),
// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 4
mt_rand(16384, 20479),
// 16 bits, 8 bits for "clk_seq_hi_res",
// 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
mt_rand(32768, 49151),
// 48 bits for "node"
mt_rand(0, 65535),
mt_rand(0, 65535),
mt_rand(0, 65535)
);
}
Returns a V5 UUID.
| Type | Description |
|---|---|
| string | Namespace |
| string | Name |
string
public static function v5($namespace, $name)
{
// Calculate hash value
$hash = sha1(static::toBin($namespace) . $name);
return sprintf
(
'%08s-%04s-%04x-%04x-%12s',
// 32 bits for "time_low"
substr($hash, 0, 8),
// 16 bits for "time_mid"
substr($hash, 8, 4),
// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 5
(hexdec(substr($hash, 12, 4)) & 0x0fff) | 0x5000,
// 16 bits, 8 bits for "clk_seq_hi_res",
// 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
(hexdec(substr($hash, 16, 4)) & 0x3fff) | 0x8000,
// 48 bits for "node"
substr($hash, 20, 12)
);
}