Skip to content

Commit

Permalink
Feat: Add $separator and $additional params to generateUsername Model…
Browse files Browse the repository at this point in the history
…CanExtend trait method.
  • Loading branch information
3m1n3nc3 committed Sep 19, 2024
1 parent d9ac395 commit 57d9d8f
Showing 1 changed file with 20 additions and 5 deletions.
25 changes: 20 additions & 5 deletions app/Traits/ModelCanExtend.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,30 @@ trait ModelCanExtend
/**
* Generate a Username for the user.
*
* @param \Illuminate\Support\Stringable|string $string
* @param string $string
* @param string $field
* @param string $separator
* @param array{class-string, string} $additional
* @return string
*/
protected static function generateUsername($string, $field = 'username')
{
$username = str($string)->slug('_');
protected static function generateUsername(
string $string,
string $field = 'username',
string $separator = '_',
array $additional = []
) {
$username = str($string)->slug($separator);

if (static::where($field, $username)->exists()) {
$username = $username->append('-')->append(Random::number(1111, 9999));
$username = $username->append($separator)->append(Random::number(1111, 9999));
}

if (
isset($additional[0]) &&
method_exists($additional[0], 'where') &&
static::where($additional[0], $additional[1] ?? $field)->exists()
) {
$username = $username->append($separator)->append(Random::number(1111, 9999));
}

return $username->toString();
Expand Down

0 comments on commit 57d9d8f

Please sign in to comment.