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 {
|
|
|
|
|
|
|
|
/**
|
2019-07-15 04:29:56 +05:30
|
|
|
* @var callable The function that will be called to generate the key.
|
|
|
|
* Must return a random value suitable for model logic.
|
|
|
|
* The function will be called in the do-while loop to avoid duplicate strings by the primary key,
|
|
|
|
* so if the function returns a static value, the program will loop forever and something will die.
|
|
|
|
* Don't do so.
|
2016-08-21 03:52:14 +05:30
|
|
|
*/
|
|
|
|
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.');
|
|
|
|
}
|
|
|
|
|
|
|
|
return $primaryKeys[0];
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|