first commit.
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "id",
|
||||
"version": "0.1.0",
|
||||
"description": "Identificadores ULID (Ulid)",
|
||||
"core": { "requires": ">=0.1", "tested": "0.1" },
|
||||
"php": ">=8.1",
|
||||
"components": {
|
||||
"ulid": { "files": ["src/Libs/Ulid.php"] }
|
||||
},
|
||||
"default": ["ulid"]
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user