2016-08-21 03:52:14 +05:30
|
|
|
|
<?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;
|
|
|
|
|
|
2019-02-26 04:56:02 +05:30
|
|
|
|
public function events(): array {
|
2016-08-21 03:52:14 +05:30
|
|
|
|
return [
|
|
|
|
|
ActiveRecord::EVENT_BEFORE_INSERT => 'setPrimaryKeyValue',
|
|
|
|
|
];
|
|
|
|
|
}
|
|
|
|
|
|
2018-04-18 02:17:25 +05:30
|
|
|
|
public function setPrimaryKeyValue(): bool {
|
2016-08-21 04:51:39 +05:30
|
|
|
|
if ($this->owner->getPrimaryKey() === null) {
|
|
|
|
|
$this->refreshPrimaryKeyValue();
|
2016-08-21 03:52:14 +05:30
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
2019-02-26 04:56:02 +05:30
|
|
|
|
public function refreshPrimaryKeyValue(): void {
|
2016-08-21 04:51:39 +05:30
|
|
|
|
do {
|
|
|
|
|
$key = $this->generateValue();
|
|
|
|
|
} while ($this->isValueExists($key));
|
|
|
|
|
|
|
|
|
|
$this->owner->{$this->getPrimaryKeyName()} = $key;
|
|
|
|
|
}
|
|
|
|
|
|
2018-04-18 02:17:25 +05:30
|
|
|
|
protected function generateValue(): string {
|
2016-08-21 03:52:14 +05:30
|
|
|
|
return (string)call_user_func($this->value);
|
|
|
|
|
}
|
|
|
|
|
|
2018-04-18 02:17:25 +05:30
|
|
|
|
protected function isValueExists(string $key): bool {
|
2019-02-26 04:56:02 +05:30
|
|
|
|
$owner = $this->owner;
|
|
|
|
|
return $owner::find()->andWhere([$this->getPrimaryKeyName() => $key])->exists();
|
2016-08-21 03:52:14 +05:30
|
|
|
|
}
|
|
|
|
|
|
2018-04-18 02:17:25 +05:30
|
|
|
|
protected function getPrimaryKeyName(): string {
|
2016-08-21 03:52:14 +05:30
|
|
|
|
$owner = $this->owner;
|
2019-02-26 04:56:02 +05:30
|
|
|
|
$primaryKeys = $owner::primaryKey();
|
2016-08-21 03:52:14 +05:30
|
|
|
|
if (!isset($primaryKeys[0])) {
|
|
|
|
|
throw new InvalidConfigException('"' . get_class($owner) . '" must have a primary key.');
|
2019-02-26 04:56:02 +05:30
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (count($primaryKeys) > 1) {
|
2016-08-21 03:52:14 +05:30
|
|
|
|
throw new InvalidConfigException('Current behavior don\'t support models with more then one primary key.');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** @noinspection PhpIncompatibleReturnTypeInspection да как бы оно всё нормально, но шторм мне не верит */
|
|
|
|
|
return $primaryKeys[0];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|