2016-11-02 01:57:38 +05:30
|
|
|
<?php
|
|
|
|
namespace common\validators;
|
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
use Closure;
|
2016-11-02 01:57:38 +05:30
|
|
|
use common\helpers\Error as E;
|
2018-01-07 21:38:40 +05:30
|
|
|
use common\helpers\StringHelper;
|
2016-11-02 01:57:38 +05:30
|
|
|
use common\models\Account;
|
|
|
|
use yii\base\Model;
|
|
|
|
use yii\db\QueryInterface;
|
|
|
|
use yii\validators;
|
|
|
|
use yii\validators\Validator;
|
|
|
|
|
|
|
|
class UsernameValidator extends Validator {
|
|
|
|
|
|
|
|
/**
|
2024-12-02 15:40:55 +05:30
|
|
|
* @phpstan-var \Closure(): int the function must return the account id for which the current validation is being performed.
|
2019-07-15 04:29:56 +05:30
|
|
|
* Allows you to skip the username check for the current account.
|
2016-11-02 01:57:38 +05:30
|
|
|
*/
|
2024-12-02 15:40:55 +05:30
|
|
|
public ?Closure $accountCallback = null;
|
2016-11-02 01:57:38 +05:30
|
|
|
|
|
|
|
public $skipOnEmpty = false;
|
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
public function validateAttribute($model, $attribute): ?array {
|
|
|
|
$filter = new validators\FilterValidator(['filter' => StringHelper::trim(...)]);
|
2016-11-02 01:57:38 +05:30
|
|
|
|
|
|
|
$required = new validators\RequiredValidator();
|
|
|
|
$required->message = E::USERNAME_REQUIRED;
|
|
|
|
|
|
|
|
$length = new validators\StringValidator();
|
|
|
|
$length->min = 3;
|
|
|
|
$length->max = 21;
|
|
|
|
$length->tooShort = E::USERNAME_TOO_SHORT;
|
|
|
|
$length->tooLong = E::USERNAME_TOO_LONG;
|
|
|
|
|
2019-04-06 07:45:23 +05:30
|
|
|
$pattern = new validators\RegularExpressionValidator(['pattern' => '/^[\p{L}\d\-_.!$%^&*()\[\]:;]+$/u']);
|
2016-11-02 01:57:38 +05:30
|
|
|
$pattern->message = E::USERNAME_INVALID;
|
|
|
|
|
|
|
|
$unique = new validators\UniqueValidator();
|
|
|
|
$unique->message = E::USERNAME_NOT_AVAILABLE;
|
|
|
|
$unique->targetClass = Account::class;
|
|
|
|
$unique->targetAttribute = 'username';
|
|
|
|
if ($this->accountCallback !== null) {
|
2024-12-02 15:40:55 +05:30
|
|
|
$unique->filter = function(QueryInterface $query): void {
|
2016-11-02 01:57:38 +05:30
|
|
|
$query->andWhere(['NOT', ['id' => ($this->accountCallback)()]]);
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2024-12-02 15:40:55 +05:30
|
|
|
$this->executeValidation($filter, $model, $attribute)
|
|
|
|
&& $this->executeValidation($required, $model, $attribute)
|
|
|
|
&& $this->executeValidation($length, $model, $attribute)
|
|
|
|
&& $this->executeValidation($pattern, $model, $attribute)
|
|
|
|
&& $this->executeValidation($unique, $model, $attribute);
|
|
|
|
|
|
|
|
return null;
|
2016-11-02 01:57:38 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
protected function executeValidation(Validator $validator, Model $model, string $attribute) {
|
|
|
|
$validator->validateAttribute($model, $attribute);
|
|
|
|
|
|
|
|
return !$model->hasErrors($attribute);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|