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
10 changes: 8 additions & 2 deletions src/Traits/RandomStringTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,14 @@ public function randomString($length = 10)
if (!is_numeric($length) || $length <= 0) {
$length = 10;
}
Comment thread
steinkel marked this conversation as resolved.
$string = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$length = (int)$length;
$alphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$alphabetLength = strlen($alphabet);
$result = '';
for ($i = 0; $i < $length; $i++) {
$result .= $alphabet[random_int(0, $alphabetLength - 1)];
}

return substr(str_shuffle($string), 0, $length);
return $result;
}
}
31 changes: 21 additions & 10 deletions tests/TestCase/Traits/RandomStringTraitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,18 +33,29 @@ public function tearDown(): void
parent::tearDown();
}

public function testRandomString()
public function testRandomStringLength()
{
$result = $this->Trait->randomString();
$this->assertEquals(10, strlen($result));

$result = $this->Trait->randomString(30);
$this->assertEquals(30, strlen($result));
$this->assertSame(10, strlen($this->Trait->randomString()));
$this->assertSame(30, strlen($this->Trait->randomString(30)));
$this->assertSame(10, strlen($this->Trait->randomString('-300')));
$this->assertSame(10, strlen($this->Trait->randomString('text')));
}

$result = $this->Trait->randomString('-300');
$this->assertEquals(10, strlen($result));
public function testRandomStringUsesSecureRandomness()
{
$first = $this->Trait->randomString(32);
$second = $this->Trait->randomString(32);

$this->assertSame(32, strlen($first));
$this->assertSame(32, strlen($second));
$this->assertNotSame($first, $second);
$this->assertMatchesRegularExpression('/^[0-9a-zA-Z]+$/', $first);
$this->assertMatchesRegularExpression('/^[0-9a-zA-Z]+$/', $second);
}

$result = $this->Trait->randomString('text');
$this->assertEquals(10, strlen($result));
public function testRandomStringOddLength()
{
$this->assertSame(31, strlen($this->Trait->randomString(31)));
$this->assertSame(1, strlen($this->Trait->randomString(1)));
}
}
Loading