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
4 changes: 4 additions & 0 deletions src/Crypt.php
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,10 @@ public static function getOptionsBcrypt(): array
*/
public static function getRandomString(int $length = 64, ?string $characters = null): string
{
if ($length < 1) {
throw new CryptException(\sprintf('Length must be greater than 0: %d', $length));
}

$initialCharacters = null;
if ($characters !== null) {
$initialCharacters = static::getCharactersForRandomString();
Expand Down
12 changes: 12 additions & 0 deletions tests/CryptTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,9 @@ public function testGetRandomString(): void
$randomString = Crypt::getRandomString();
static::assertSame(64, \mb_strlen($randomString));

$randomString = Crypt::getRandomString(1);
static::assertSame(1, \mb_strlen($randomString));

$randomString = Crypt::getRandomString(105);
static::assertSame(105, \mb_strlen($randomString));

Expand All @@ -297,6 +300,15 @@ public function testGetRandomString(): void
static::assertNotSame('a', Crypt::getCharactersForRandomString());
}

/** @throws CryptException */
public function testInvalidLengthGetRandomStringCryptException(): void
{
$this->expectException(CryptException::class);
$this->expectExceptionMessage('Length must be greater than 0: 0');

Crypt::getRandomString(0, '');
}

/** @throws CryptException */
public function testGetRandomStringCryptException(): void
{
Expand Down
Loading