diff --git a/docker-compose.yml b/docker-compose.yml index 03d83cb..aa16942 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -2,7 +2,7 @@ services: ulid-php-lib: build: context: ./ - dockerfile: ./ops/Dockerfile + dockerfile: ./contrib/Dockerfile container_name: ulid-php-lib volumes: - ./:/var/www/html diff --git a/src/Ulid.php b/src/Ulid.php index d0d4bef..ea92cc3 100755 --- a/src/Ulid.php +++ b/src/Ulid.php @@ -16,13 +16,17 @@ class Ulid * @param string $ulid * @return bool */ - public function isValidFormat( - string $ulid - ): bool { + public function isValidFormat(string $ulid): bool + { $validator = UlidConstants::TIME_LENGTH + UlidConstants::RANDOM_LENGTH; + if (strlen($ulid) !== $validator) { return false; } + + if (!preg_match(UlidConstants::REGEX, $ulid)) { + return false; + } return true; } @@ -155,9 +159,9 @@ public function generate( $encodingChars = UlidConstants::CHARS; for ($i = 9; $i >= 0; $i--) { - $mod = $time % UlidConstants::LENGHT; + $mod = $time % UlidConstants::LENGTH; $timeChars = $encodingChars[$mod] . $timeChars; - $time = ($time - $mod) / UlidConstants::LENGHT; + $time = ($time - $mod) / UlidConstants::LENGTH; } $this->hasIncrementLastRandChars( @@ -195,7 +199,7 @@ public function decodeTime( if ($encodingIndex === false) { throw new Exception('Invalid ULID character: ' . $char); } - $exponential = pow(UlidConstants::LENGHT, $index); + $exponential = pow(UlidConstants::LENGTH, $index); $carry += ($encodingIndex * $exponential); } diff --git a/src/UlidConstants.php b/src/UlidConstants.php index 992a9c2..d0936d6 100755 --- a/src/UlidConstants.php +++ b/src/UlidConstants.php @@ -5,8 +5,9 @@ class UlidConstants { const CHARS = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'; - const LENGHT = 32; + const LENGTH = 32; const TIME_MAX = 281474976710655; const TIME_LENGTH = 10; const RANDOM_LENGTH = 16; + const REGEX = '/^[0-9A-HJKMNP-TV-Z]{26}$/ '; } diff --git a/tests/UlidTest.php b/tests/UlidTest.php index 5689cdf..6351b95 100755 --- a/tests/UlidTest.php +++ b/tests/UlidTest.php @@ -230,6 +230,32 @@ public function testDecodeTimeInvalidTime() $ulid->decodeTime('QS234SAD23RADSWRA3FADQ3RS2'); } + /** + * @covers Ulid\Ulid::isValidFormat + */ + public function testIsInvalidCharactersFormat() + { + $ulid = new Ulid(); + + $invalidUlid = '%%%%%%%%%%%%%%%%%%%%%%%%%%'; + + $result = $ulid->isValidFormat($invalidUlid); + + $this->assertFalse($result); + } + + /** + * @covers Ulid\Ulid::isValidFormat + */ + public function testIsValidFormatDoesNotValidateCharacters() + { + $ulid = new Ulid(); + + $result = $ulid->isValidFormat('01E475VQGHNW990PVHXFDT4C6W'); + + $this->assertTrue($result); + } + protected function tearDown(): void { //