Skip to content

Commit 8e425fd

Browse files
committed
add password method
1 parent 67c19a7 commit 8e425fd

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

src/Illuminate/Support/Str.php

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -721,6 +721,54 @@ public static function pluralStudly($value, $count = 2)
721721
return implode('', $parts).self::plural($lastWord, $count);
722722
}
723723

724+
/**
725+
* Generate a random, secure password.
726+
*
727+
* @param int $length
728+
* @param bool $letters
729+
* @param bool $numbers
730+
* @param bool $symbols
731+
* @return string
732+
*/
733+
public static function password($length = 32, $letters = true, $numbers = true, $symbols = true)
734+
{
735+
$characters = [];
736+
737+
if ($letters) {
738+
$characters = array_merge($characters, [
739+
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
740+
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
741+
'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
742+
'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
743+
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
744+
]);
745+
}
746+
747+
if ($numbers) {
748+
$characters = array_merge($characters, [
749+
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
750+
]);
751+
}
752+
753+
if ($symbols) {
754+
$characters = array_merge($characters, [
755+
'~', '!', '#', '$', '%', '^', '&', '*', '(', ')', '-',
756+
'_', '.', ',', '<', '>', '?', '/', '\\', '{', '}', '[',
757+
']', '|', ':', ';',
758+
]);
759+
}
760+
761+
$password = '';
762+
763+
$possible = count($characters) - 1;
764+
765+
for ($i = 0; $i < $length; $i++) {
766+
$password = $password.$characters[random_int(0, $possible)];
767+
}
768+
769+
return $password;
770+
}
771+
724772
/**
725773
* Generate a more truly "random" alpha-numeric string.
726774
*

tests/Support/SupportStrTest.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1083,6 +1083,11 @@ public function testItCanSpecifyAFallbackForASequence()
10831083
Str::createUuidsNormally();
10841084
}
10851085
}
1086+
1087+
public function testPasswordCreation()
1088+
{
1089+
$this->assertTrue(strlen(Str::password()) === 32);
1090+
}
10861091
}
10871092

10881093
class StringableObjectStub

0 commit comments

Comments
 (0)