Логика генерации значения первичного ключа для строк вынесена в поведение

This commit is contained in:
ErickSkrauch
2016-08-21 01:22:14 +03:00
parent 59f51451d0
commit 53d56d6b97
4 changed files with 138 additions and 48 deletions

View File

@@ -3,6 +3,7 @@ namespace common\models;
use common\behaviors\DataBehavior;
use common\behaviors\EmailActivationExpirationBehavior;
use common\behaviors\PrimaryKeyValueBehavior;
use common\components\UserFriendlyRandomKey;
use yii\base\InvalidConfigException;
use yii\behaviors\TimestampBehavior;
@@ -42,6 +43,12 @@ class EmailActivation extends ActiveRecord {
'class' => TimestampBehavior::class,
'updatedAtAttribute' => false,
],
[
'class' => PrimaryKeyValueBehavior::class,
'value' => function() {
return UserFriendlyRandomKey::make();
},
],
'expirationBehavior' => [
'class' => EmailActivationExpirationBehavior::class,
'repeatTimeout' => 5 * 60, // 5m
@@ -84,26 +91,4 @@ class EmailActivation extends ActiveRecord {
];
}
public function beforeSave($insert) {
if (!parent::beforeSave($insert)) {
return false;
}
if ($this->key === null) {
do {
$this->key = $this->generateKey();
} while ($this->isKeyExists($this->key));
}
return true;
}
protected function generateKey() : string {
return UserFriendlyRandomKey::make();
}
protected function isKeyExists(string $key) : bool {
return self::find()->andWhere(['key' => $key])->exists();
}
}