1 | <?php |
||
58 | class OptimisticLockBehavior extends AttributeBehavior |
||
59 | { |
||
60 | /** |
||
61 | * {@inheritdoc} |
||
62 | * |
||
63 | * In case of `null` value it will be directly parsed from [[\yii\web\Request::getBodyParam()|getBodyParam()]] or set to 0. |
||
64 | */ |
||
65 | public $value; |
||
66 | /** |
||
67 | * {@inheritdoc} |
||
68 | */ |
||
69 | public $skipUpdateOnClean = false; |
||
70 | /** |
||
71 | * @var string the attribute name holding the version value. |
||
72 | */ |
||
73 | private $_lockAttribute; |
||
74 | |||
75 | |||
76 | /** |
||
77 | * {@inheritdoc} |
||
78 | */ |
||
79 | 1 | public function attach($owner) |
|
88 | |||
89 | /** |
||
90 | * {@inheritdoc} |
||
91 | */ |
||
92 | 1 | public function events() |
|
93 | { |
||
94 | 1 | return Yii::$app->request instanceof \yii\web\Request ? [ |
|
95 | BaseActiveRecord::EVENT_BEFORE_INSERT => 'evaluateAttributes', |
||
96 | BaseActiveRecord::EVENT_BEFORE_UPDATE => 'evaluateAttributes', |
||
97 | BaseActiveRecord::EVENT_BEFORE_DELETE => 'evaluateAttributes', |
||
98 | 1 | ] : []; |
|
99 | } |
||
100 | |||
101 | /** |
||
102 | * Returns the column name to hold the version value as defined in [[\yii\db\BaseActiveRecord::optimisticLock()|optimisticLock()]]. |
||
103 | * @return string the property name. |
||
104 | * @throws InvalidCallException if [[\yii\db\BaseActiveRecord::optimisticLock()|optimisticLock()]] is not properly configured. |
||
105 | * @since 2.0.16 |
||
106 | */ |
||
107 | 1 | protected function getLockAttribute() |
|
122 | |||
123 | /** |
||
124 | * {@inheritdoc} |
||
125 | * |
||
126 | * In case of `null`, value will be parsed from [[\yii\web\Request::getBodyParam()|getBodyParam()]] or set to 0. |
||
127 | */ |
||
128 | protected function getValue($event) |
||
129 | { |
||
130 | if ($this->value === null) { |
||
131 | $lock = $this->getLockAttribute(); |
||
132 | $input = Yii::$app->getRequest()->getBodyParam($lock); |
||
133 | $isValid = $input && (new NumberValidator())->validate($input); |
||
134 | return $isValid ? $input : 0; |
||
135 | } |
||
136 | |||
137 | return parent::getValue($event); |
||
138 | } |
||
139 | |||
140 | /** |
||
141 | * Upgrades the version value by one and stores it to database. |
||
142 | * |
||
143 | * ```php |
||
144 | * $model->upgrade(); |
||
145 | * ``` |
||
146 | * @throws InvalidCallException if owner is a new record. |
||
147 | * @since 2.0.16 |
||
148 | */ |
||
149 | 1 | public function upgrade() |
|
160 | } |
||
161 |