2016-05-15 04:03:21 +05:30
|
|
|
|
<?php
|
|
|
|
|
namespace api\validators;
|
|
|
|
|
|
2016-06-17 02:02:23 +05:30
|
|
|
|
use common\helpers\Error as E;
|
2016-05-15 04:03:21 +05:30
|
|
|
|
use common\models\EmailActivation;
|
|
|
|
|
use yii\validators\Validator;
|
|
|
|
|
|
2016-12-23 02:51:05 +05:30
|
|
|
|
/**
|
|
|
|
|
* Валидатор для проверки полученного от пользователя кода активации.
|
|
|
|
|
* В случае успешной валидации подменяет значение поля на актуальную модель
|
|
|
|
|
*/
|
2016-05-15 04:03:21 +05:30
|
|
|
|
class EmailActivationKeyValidator extends Validator {
|
|
|
|
|
|
2016-12-23 02:51:05 +05:30
|
|
|
|
/**
|
|
|
|
|
* @var int тип ключа. Если не указан, то валидирует по всем ключам.
|
|
|
|
|
*/
|
|
|
|
|
public $type;
|
|
|
|
|
|
|
|
|
|
public $keyRequired = E::KEY_REQUIRED;
|
|
|
|
|
|
2016-06-17 02:02:23 +05:30
|
|
|
|
public $notExist = E::KEY_NOT_EXISTS;
|
2016-05-15 04:03:21 +05:30
|
|
|
|
|
2016-06-17 02:02:23 +05:30
|
|
|
|
public $expired = E::KEY_EXPIRE;
|
2016-05-15 04:03:21 +05:30
|
|
|
|
|
2016-12-23 02:51:05 +05:30
|
|
|
|
public function validateAttribute($model, $attribute) {
|
|
|
|
|
$value = $model->$attribute;
|
|
|
|
|
if (empty($value)) {
|
|
|
|
|
$this->addError($model, $attribute, $this->keyRequired);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$activation = $this->findEmailActivationModel($value, $this->type);
|
|
|
|
|
if ($activation === null) {
|
|
|
|
|
$this->addError($model, $attribute, $this->notExist);
|
|
|
|
|
return;
|
2016-05-15 04:03:21 +05:30
|
|
|
|
}
|
|
|
|
|
|
2016-12-23 02:51:05 +05:30
|
|
|
|
if ($activation->isExpired()) {
|
|
|
|
|
$this->addError($model, $attribute, $this->expired);
|
|
|
|
|
return;
|
2016-05-15 04:03:21 +05:30
|
|
|
|
}
|
|
|
|
|
|
2016-12-23 02:51:05 +05:30
|
|
|
|
$model->$attribute = $activation;
|
2016-05-15 04:03:21 +05:30
|
|
|
|
}
|
|
|
|
|
|
2016-12-23 02:51:05 +05:30
|
|
|
|
protected function findEmailActivationModel(string $key, int $type = null): ?EmailActivation {
|
|
|
|
|
$query = EmailActivation::find();
|
|
|
|
|
$query->andWhere(['key' => $key]);
|
|
|
|
|
if ($type !== null) {
|
|
|
|
|
$query->andWhere(['type' => $type]);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return $query->one();
|
2016-05-15 04:03:21 +05:30
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|