Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 10 additions & 6 deletions src/Ulid.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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);
}

Expand Down
3 changes: 2 additions & 1 deletion src/UlidConstants.php
Original file line number Diff line number Diff line change
Expand Up @@ -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}$/ ';
}
26 changes: 26 additions & 0 deletions tests/UlidTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
//
Expand Down