Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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: 1 addition & 3 deletions src/Traits/RandomStringTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,6 @@ public function randomString($length = 10)
if (!is_numeric($length) || $length <= 0) {
$length = 10;
}
Comment thread
steinkel marked this conversation as resolved.
$string = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

return substr(str_shuffle($string), 0, $length);
return substr(bin2hex(random_bytes((int)ceil($length / 2))), 0, $length);
Comment thread
steinkel marked this conversation as resolved.
Outdated
}
}
23 changes: 13 additions & 10 deletions tests/TestCase/Traits/RandomStringTraitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,18 +33,21 @@ 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);

$result = $this->Trait->randomString('text');
$this->assertEquals(10, strlen($result));
$this->assertNotSame($first, $second);
$this->assertMatchesRegularExpression('/^[0-9a-f]+$/', $first);
$this->assertMatchesRegularExpression('/^[0-9a-f]+$/', $second);
Comment thread
steinkel marked this conversation as resolved.
Outdated
}
}
Loading