Skip to content
This repository was archived by the owner on Mar 5, 2025. It is now read-only.

Making random username generation more efficient. #1467

Merged
merged 2 commits into from
May 3, 2017
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
3 changes: 2 additions & 1 deletion src/Robo/Commands/Drupal/DrupalCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ public function install() {
$username = RandomString::string(10, FALSE,
function ($string) {
return !preg_match('/[^\x{80}-\x{F7} a-z0-9@+_.\'-]/i', $string);
}
},
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!#%^&*()_-?/.,+=><'
);

$task = $this->taskDrush()
Expand Down
14 changes: 12 additions & 2 deletions src/Robo/Common/RandomString.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,19 @@ class RandomString {
* Defaults to FALSE.
* @param callable $validator
* (optional) A callable to validate the string. Defaults to NULL.
* @param string $characters
* (optional) A string containing all possible characters that may be used
* to generate the random string.
*
* @return string
* Randomly generated string.
*
* @see \Drupal\Component\Utility\Random::name()
*/
public static function string($length = 8, $unique = FALSE, callable $validator = NULL) {
public static function string($length = 8, $unique = FALSE, callable $validator = NULL, $characters = '') {
$counter = 0;
$strings = [];
$characters_array = $characters ? str_split($characters) : [];

// Continue to loop if $unique is TRUE and the generated string is not
// unique or if $validator is a callable that returns FALSE. To generate a
Expand All @@ -50,7 +54,13 @@ public static function string($length = 8, $unique = FALSE, callable $validator
}
$str = '';
for ($i = 0; $i < $length; $i++) {
$str .= chr(mt_rand(32, 126));
if ($characters_array) {
$position = mt_rand(0, count($characters_array) - 1);
$str .= $characters_array[$position];
}
else {
$str .= chr(mt_rand(32, 126));
}
}
$counter++;

Expand Down