Skip to content

Commit

Permalink
making it stateless, increasing time precision, replace assertRegExp(…
Browse files Browse the repository at this point in the history
…) with assertMatchesRegularExpression()
  • Loading branch information
mambax7 committed Oct 3, 2023
1 parent 18eac06 commit 88d3911
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 20 deletions.
16 changes: 1 addition & 15 deletions src/Ulid.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,6 @@ class Ulid
{
const ENCODING_CHARS = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
const ENCODING_LENGTH = 32;
/**
* Last generated timestamp.
* @var int
*/
private static $lastTime = 0;

/**
* Generate a new ULID.
Expand All @@ -39,16 +34,7 @@ class Ulid

public static function generate(bool $upperCase = true): string
{
$time = (int)(microtime(true) * 1000);

// If the current timestamp is equal or less than the last generated one,
// increase it by one millisecond to ensure ULIDs are always sorted correctly.
if ($time <= self::$lastTime) {
$time = self::$lastTime + 1;
}

self::$lastTime = $time;

$time = (int)(microtime(true) * 1000000);
$timeChars = self::encodeTime($time);
$randChars = self::encodeRandomness();
$ulid = $timeChars . $randChars;
Expand Down
13 changes: 8 additions & 5 deletions tests/unit/UlidTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@ class UlidTest extends \PHPUnit\Framework\TestCase
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
protected function setUp(): void
{
}

/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown()
protected function tearDown(): void
{
}

Expand All @@ -26,15 +26,18 @@ protected function tearDown()
*/
public function testGenerate()
{
$ulid = Ulid::generate();
$ulid1 = Ulid::generate();
usleep(2000); // Wait for 2 milliseconds to ensure a different timestamp
$ulid2 = Ulid::generate();

$this->assertRegExp('/^[0-9A-Z]{26}$/', \strtoupper($ulid));
$this->assertNotEquals($ulid1, $ulid2, 'ULIDs should be unique');
$this->assertTrue(strcasecmp($ulid1, $ulid2) < 0, 'ULIDs should collate correctly');
}
public function testGeneratesLowercaseIdentifierWhenConfigured(): void
{
$ulid = Ulid::generate(false); //generate lower case

$this->assertRegExp('/[0-9][a-z]/', $ulid);
$this->assertMatchesRegularExpression('/[0-9][a-z]/', $ulid);
}

public function testGeneratesTwentySixChars(): void
Expand Down

0 comments on commit 88d3911

Please sign in to comment.