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

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

@@ -0,0 +1,61 @@
<?php
namespace common\behaviors;
use yii\base\Behavior;
use yii\base\InvalidConfigException;
use yii\db\ActiveRecord;
/**
* @property ActiveRecord $owner
*/
class PrimaryKeyValueBehavior extends Behavior {
/**
* @var callable Функция, что будет вызвана для генерации ключа.
* Должна возвращать случайное значение, подходящее для логики модели. Функция будет вызываться
* в цикле do-while с целью избежания дубликатов строк по первичному ключу, так что если функция
* станет возвращать статичное значение, то программа зациклится и что-нибудь здохнет. Не делайте так.
*/
public $value;
public function events() {
return [
ActiveRecord::EVENT_BEFORE_INSERT => 'setPrimaryKeyValue',
];
}
public function setPrimaryKeyValue() : bool {
$owner = $this->owner;
if ($owner->getPrimaryKey() === null) {
do {
$key = $this->generateValue();
} while ($this->isValueExists($key));
$owner->{$this->getPrimaryKeyName()} = $key;
}
return true;
}
protected function generateValue() : string {
return (string)call_user_func($this->value);
}
protected function isValueExists(string $key) : bool {
return $this->owner->find()->andWhere([$this->getPrimaryKeyName() => $key])->exists();
}
protected function getPrimaryKeyName() : string {
$owner = $this->owner;
$primaryKeys = $owner->primaryKey();
if (!isset($primaryKeys[0])) {
throw new InvalidConfigException('"' . get_class($owner) . '" must have a primary key.');
} elseif (count($primaryKeys) > 1) {
throw new InvalidConfigException('Current behavior don\'t support models with more then one primary key.');
}
/** @noinspection PhpIncompatibleReturnTypeInspection да как бы оно всё нормально, но шторм мне не верит */
return $primaryKeys[0];
}
}

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();
}
}