diff --git a/src/Ulid.php b/src/Ulid.php index 86ac5fe..0590d8d 100644 --- a/src/Ulid.php +++ b/src/Ulid.php @@ -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. @@ -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; diff --git a/tests/unit/UlidTest.php b/tests/unit/UlidTest.php index 7820e81..7c20ec5 100644 --- a/tests/unit/UlidTest.php +++ b/tests/unit/UlidTest.php @@ -9,7 +9,7 @@ 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 { } @@ -17,7 +17,7 @@ protected function setUp() * 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 { } @@ -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