You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
pixelfed/app/Rules/ValidUsername.php

69 lines
1.9 KiB
PHTML

<?php
namespace App\Rules;
use App\Util\Lexer\RestrictedNames;
9 months ago
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Str;
use Illuminate\Translation\PotentiallyTranslatedString;
class ValidUsername implements ValidationRule
{
/**
* Run the validation rule.
*
* @param Closure(string): PotentiallyTranslatedString $fail
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
$dash = substr_count($value, '-');
$underscore = substr_count($value, '_');
$period = substr_count($value, '.');
if (Str::endsWith($value, ['.php', '.js', '.css'])) {
$fail('Username is invalid.');
9 months ago
return;
}
if (($dash + $underscore + $period) > 1) {
$fail('Username is invalid. Can only contain one dash (-), period (.) or underscore (_).');
9 months ago
return;
}
if (! ctype_alnum($value[0])) {
$fail('Username is invalid. Must start with a letter or number.');
9 months ago
return;
}
if (! ctype_alnum($value[strlen($value) - 1])) {
$fail('Username is invalid. Must end with a letter or number.');
9 months ago
return;
}
$val = str_replace(['_', '.', '-'], '', $value);
if (! ctype_alnum($val)) {
$fail('Username is invalid. Username must be alpha-numeric and may contain dashes (-), periods (.) and underscores (_).');
9 months ago
return;
}
// if (! preg_match('/[a-zA-Z]/', $value)) {
// $fail('Username is invalid. Must contain at least one alphabetical character.');
// return;
// }
$restricted = RestrictedNames::get();
if (in_array(strtolower($value), array_map('strtolower', $restricted))) {
$fail('Username cannot be used.');
9 months ago
return;
}
}
}