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
|
|
|
/**
|
2019-07-15 04:29:56 +05:30
|
|
|
* Validator to check the activation code received from the user.
|
|
|
|
* In case of success it replaces the field value with the corresponding model.
|
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
|
|
|
/**
|
2019-07-15 04:29:56 +05:30
|
|
|
* @var int the type of key. If not specified, it validates over all keys.
|
2016-12-23 02:51:05 +05:30
|
|
|
*/
|
|
|
|
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 03:52:51 +05:30
|
|
|
public $skipOnEmpty = false;
|
|
|
|
|
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
|
|
|
}
|
|
|
|
|
|
|
|
}
|