Skip to content

Commit 8ae0eb4

Browse files
Merge pull request #87 from utopia-php/feat-generate-random-ids
Feat: pad uniqid with random bytes
2 parents 75f206d + 3ba5593 commit 8ae0eb4

2 files changed

Lines changed: 24 additions & 4 deletions

File tree

src/Database/Database.php

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1174,13 +1174,22 @@ protected function decodeAttribute(string $name, $value, Document $document)
11741174
}
11751175

11761176
/**
1177-
* Get 13 Chars Unique ID.
1178-
*
1177+
* Get Unique ID
1178+
*
1179+
* @param int $padding extra random bytes to append to 13-char uniqid
1180+
*
11791181
* @return string
11801182
*/
1181-
public function getId(): string
1183+
public function getId(int $padding = 0): string
11821184
{
1183-
return \uniqid();
1185+
$uniqid = \uniqid();
1186+
1187+
if ($padding > 0) {
1188+
$bytes = \random_bytes(\ceil($padding / 2)); // one byte expands to two chars
1189+
$uniqid .= \substr(\bin2hex($bytes), 0, $padding);
1190+
}
1191+
1192+
return $uniqid;
11841193
}
11851194

11861195
/**

tests/Database/Base.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1680,4 +1680,15 @@ public function testGetIndexLimit()
16801680
{
16811681
$this->assertEquals(61, $this->getDatabase()->getIndexLimit());
16821682
}
1683+
1684+
public function testGetId()
1685+
{
1686+
$this->assertEquals(13, strlen($this->getDatabase()->getId()));
1687+
$this->assertEquals(13, strlen($this->getDatabase()->getId(0)));
1688+
$this->assertEquals(13, strlen($this->getDatabase()->getId(-1)));
1689+
$this->assertEquals(23, strlen($this->getDatabase()->getId(10)));
1690+
1691+
// ensure two sequential calls to getId do not give the same result
1692+
$this->assertNotEquals($this->getDatabase()->getId(10), $this->getDatabase()->getId(10));
1693+
}
16831694
}

0 commit comments

Comments
 (0)