123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172 |
- <?php
- namespace yii\behaviors;
- use Yii;
- use yii\db\BaseActiveRecord;
- use yii\base\InvalidCallException;
- use yii\validators\NumberValidator;
- use yii\helpers\ArrayHelper;
- class OptimisticLockBehavior extends AttributeBehavior
- {
-
- public $value;
-
- public $skipUpdateOnClean = false;
-
- private $_lockAttribute;
-
- public function attach($owner)
- {
- parent::attach($owner);
- if (empty($this->attributes)) {
- $lock = $this->getLockAttribute();
- $this->attributes = array_fill_keys(array_keys($this->events()), $lock);
- }
- }
-
- public function events()
- {
- return Yii::$app->request instanceof \yii\web\Request ? [
- BaseActiveRecord::EVENT_BEFORE_INSERT => 'evaluateAttributes',
- BaseActiveRecord::EVENT_BEFORE_UPDATE => 'evaluateAttributes',
- BaseActiveRecord::EVENT_BEFORE_DELETE => 'evaluateAttributes',
- ] : [];
- }
-
- protected function getLockAttribute()
- {
- if ($this->_lockAttribute) {
- return $this->_lockAttribute;
- }
-
- $owner = $this->owner;
- $lock = $owner->optimisticLock();
- if ($lock === null || $owner->hasAttribute($lock) === false) {
- throw new InvalidCallException("Unable to get the optimistic lock attribute. Probably 'optimisticLock()' method is misconfigured.");
- }
- $this->_lockAttribute = $lock;
- return $lock;
- }
-
- protected function getValue($event)
- {
- if ($this->value === null) {
- $request = Yii::$app->getRequest();
- $lock = $this->getLockAttribute();
- $formName = $this->owner->formName();
- $formValue = $formName ? ArrayHelper::getValue($request->getBodyParams(), $formName . '.' . $lock) : null;
- $input = $formValue ?: $request->getBodyParam($lock);
- $isValid = $input && (new NumberValidator())->validate($input);
- return $isValid ? $input : 0;
- }
- return parent::getValue($event);
- }
-
- public function upgrade()
- {
-
- $owner = $this->owner;
- if ($owner->getIsNewRecord()) {
- throw new InvalidCallException('Upgrading the model version is not possible on a new record.');
- }
- $lock = $this->getLockAttribute();
- $version = $owner->$lock ?: 0;
- $owner->updateAttributes([$lock => $version + 1]);
- }
- }
|