first commit.

This commit is contained in:
kj
2026-10-05 15:08:39 -03:00
commit b7799f9fff
93 changed files with 8966 additions and 0 deletions
+83
View File
@@ -0,0 +1,83 @@
<?php
namespace Libs;
/**
* ULID (Universally Unique Lexicographically Sortable Identifier) implementation.
*
* @author KJ
* @website https://kj2.me
* @license MIT
*/
class Ulid
{
public const ENCODING_CHARS = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
public const ENCODING_LENGTH = 32;
public const RANDOM_LENGTH = 16;
public const TIME_LENGTH = 10;
/**
* @var int
*/
private static $lastGenTime = 0;
/**
* @var array
*/
private static $lastRandChars = [];
/**
* Generates a unique ULID.
*
* Borrowed from robinvdvleuten/ulid
*
* @return string
*/
public static function generate(): string
{
$timestamp = (int) (microtime(true) * 1000);
$duplicateTime = $timestamp === static::$lastGenTime;
static::$lastGenTime = $timestamp;
$timeChars = '';
$randChars = '';
for ($i = static::TIME_LENGTH - 1; $i >= 0; $i--) {
$mod = $timestamp % static::ENCODING_LENGTH;
$timeChars = static::ENCODING_CHARS[$mod] . $timeChars;
$timestamp = ($timestamp - $mod) / static::ENCODING_LENGTH;
}
if (!$duplicateTime) {
for ($i = 0; $i < static::RANDOM_LENGTH; $i++) {
static::$lastRandChars[$i] = random_int(0, 31);
}
} else {
for ($i = static::RANDOM_LENGTH - 1; $i >= 0 && static::$lastRandChars[$i] === 31; $i--) {
static::$lastRandChars[$i] = 0;
}
static::$lastRandChars[$i]++;
}
for ($i = 0; $i < static::RANDOM_LENGTH; $i++) {
$randChars .= static::ENCODING_CHARS[static::$lastRandChars[$i]];
}
return $timeChars . $randChars;
}
/**
* Validates a ULID.
*
* @param string $ulid
*
* @return bool
*/
public static function validate(string $ulid): bool
{
return (bool) preg_match('/^[0-9A-HJKMNPQRSTVWXYZ]{26}$/', strtoupper($ulid));
}
}