Skip to content

Commit

Permalink
Merge pull request #23 from PhpGt/20-length
Browse files Browse the repository at this point in the history
feature: set length in constructor
  • Loading branch information
g105b authored Sep 24, 2022
2 parents 4dd73a8 + c2fb8e9 commit f7f8a95
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 10 deletions.
26 changes: 17 additions & 9 deletions src/Ulid.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,17 @@
use Stringable;

class Ulid implements Stringable {
const TOTAL_LENGTH = 20;
const TIMESTAMP_LENGTH = 10;
const DEFAULT_TOTAL_LENGTH = 20;
const DEFAULT_TIMESTAMP_LENGTH = 10;

private float $timestamp;
private string $randomString;

public function __construct(float|int $init = null) {
public function __construct(
float|int $init = null,
private int $length = self::DEFAULT_TOTAL_LENGTH,
private int $timestampLength = self::DEFAULT_TIMESTAMP_LENGTH,
) {
if(!is_null($init)) {
$timestamp = $init;
}
Expand All @@ -21,7 +25,7 @@ public function __construct(float|int $init = null) {
$this->timestamp = $timestamp;

$this->randomString = "";
for($i = 0; $i < self::TOTAL_LENGTH - self::TIMESTAMP_LENGTH; $i++) {
for($i = 0; $i < $this->length - $this->timestampLength; $i++) {
$rnd = random_int(0, 31);
$this->randomString .= $this->base32(
$rnd
Expand All @@ -45,11 +49,15 @@ public function getTimestamp():float {
public function getTimestampString():string {
$t = round($this->timestamp * 1000);
$base32Timestamp = $this->base32((int)$t);
return str_pad(
$base32Timestamp,
self::TIMESTAMP_LENGTH,
"0",
STR_PAD_LEFT
return substr(
str_pad(
$base32Timestamp,
$this->timestampLength,
"0",
STR_PAD_LEFT
),
0,
$this->timestampLength,
);
}

Expand Down
20 changes: 19 additions & 1 deletion test/phpunit/UlidTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public function testToString_length():void {
// Testing multiple times in case randomness causes different length strings.
for($i = 0; $i < 1_000; $i++) {
$sut = (string)(new Ulid(0));
self::assertSame(Ulid::TOTAL_LENGTH, strlen($sut));
self::assertSame(Ulid::DEFAULT_TOTAL_LENGTH, strlen($sut));
}
}

Expand All @@ -63,4 +63,22 @@ public function testToString_sameEachTime():void {
$string2 = (string)$sut;
self::assertSame($string1, $string2);
}

public function testConstruct_setLength():void {
for($i = 0; $i < 10; $i++) {
$length = rand(10, 100);
$sut = new Ulid(length: $length);
self::assertSame($length, strlen($sut));
}
}

public function testConstruct_setTimestampLength():void {
for($i = 0; $i < 10; $i++) {
$tLength = rand(5, 10);
$sut = new Ulid(timestampLength: $tLength);
echo $sut, PHP_EOL;
$tString = $sut->getTimestampString();
self::assertSame($tLength, strlen($tString));
}
}
}

0 comments on commit f7f8a95

Please sign in to comment.