-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathSortable.php
243 lines (219 loc) · 7.81 KB
/
Sortable.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
<?php
/**
* MIT licence
* Version 1.2
* Sjaak Priester, Amsterdam 28-08-2014 ... 17-02-2021.
* https://sjaakpriester.nl
*
* ActiveRecord Behavior for Yii 2.0
*
* Makes an ActiveRecord sortable.
*
* Sortable maintains one or more attributes defined in Sortable::orderAttribute (default: "ord").
* The values are contiguous from 0, and define the order of the record, 0 being the first.
* The function order($newPosition, $foreignKeyName) can be used to modify the position of the record in the order.
* If $foreignKeyName is given, the ordering is restricted to records with the same value of $foreignKeyName.
* A new record is inserted at the end of the order.
*
* Version 1.1 handles the situation where the foreign key value is changed on update.
*/
namespace sjaakp\sortable;
use yii\base\Behavior;
use yii\base\Exception;
use yii\base\InvalidConfigException;
use yii\db\ActiveRecord;
use yii\db\Transaction;
/**
* Class Sortable
* @package sjaakp\sortable
* @var $owner ActiveRecord
*/
class Sortable extends Behavior {
/**
* @var string|array
* The order attribute(s) of the ActiveRecord.
* This can take the following values:
* - string - the order attribute name
* - array of:
* - string - the order attribute name,
* - foreignKeyName => orderAttrName - limit ordering to ActiveRecords with the same foreign key value
*/
public $orderAttribute = 'ord';
protected $_attributes;
public function events() {
return [
ActiveRecord::EVENT_BEFORE_INSERT => 'beforeInsert',
ActiveRecord::EVENT_BEFORE_DELETE => 'beforeDelete',
ActiveRecord::EVENT_AFTER_DELETE => 'afterDelete',
ActiveRecord::EVENT_BEFORE_UPDATE => 'beforeUpdate',
];
}
/**
* @inheritDoc
*/
public function init()
{
if (is_string($this->orderAttribute)) $this->orderAttribute = [$this->orderAttribute];
parent::init();
}
/**
* @param $event
* @throws \yii\db\Exception
*/
public function beforeInsert($event) {
$attrs = $this->owner->getAttributes();
$this->saveDelHelper([$this, 'addToOrder'], $attrs);
}
/**
* @param $event
*/
public function beforeDelete($event) {
$this->_attributes = $this->owner->getAttributes();
return true;
}
/**
* @param $event
* @throws \yii\db\Exception
* Update counters after deletion, so that order attributes can be UNIQUE
* Issue #4
*/
public function afterDelete($event) {
$this->saveDelHelper([$this, 'removeFromOrder'], $this->_attributes);
}
/**
* @param $event
* @throws \yii\db\Exception
*/
public function beforeUpdate($event) {
/**
* @var $owner ActiveRecord
* @var $trans Transaction
*/
$owner = $this->owner;
$trans = $owner->db->beginTransaction();
try {
foreach ($this->orderAttribute as $fk => $orderAttr) {
// only if foreignkey is changed...
if (! is_integer($fk) && $owner->isAttributeChanged($fk)) {
// ... remove from ordered list with old foreignkey...
$where = [ $fk => $owner->getOldAttribute($fk) ];
$this->removeFromOrder($orderAttr, $where);
// ... and add to ordered list with new foreignkey
$where = [ $fk => $owner->getAttribute($fk) ];
$this->addToOrder($orderAttr, $where);
}
}
$trans->commit();
} catch (Exception $e) {
$trans->rollBack();
}
}
protected function addToOrder($orderAttr, $where) {
/**
* @var $owner ActiveRecord
*/
$owner = $this->owner;
// insert at the end of ordered list
$owner->setAttribute($orderAttr, $owner->find()->where($where)->count());
}
protected function removeFromOrder($orderAttr, $where) {
/**
* @var $owner ActiveRecord
*/
$owner = $this->owner;
// remove from ordered list, but keep positions contiguous
// by decrementing all positions which are greater
$owner->UpdateAllCounters([$orderAttr => -1], [
'and',
$where,
"{{{$orderAttr}}} > :order"
],
[':order' => $owner->getAttribute($orderAttr)]
);
}
/**
* @param $func
* @throws \yii\db\Exception
*/
protected function saveDelHelper($func, $attributes) {
/**
* @var $owner ActiveRecord
* @var $trans Transaction
*/
$owner = $this->owner;
$trans = $owner->db->beginTransaction();
try {
foreach ($this->orderAttribute as $fk => $orderAttr) {
$where = is_integer($fk) ? 1 : [$fk => $attributes[$fk]];
call_user_func($func, $orderAttr, $where);
}
$trans->commit();
} catch (Exception $e) {
$trans->rollBack();
}
}
/**
* @param integer $newPosition zero indexed position
* @param null|string $foreignKeyName
* if null, all records are ordered
* if string, ordering is restricted to records with the same foreign key value
* @param array $where extra where condition
* @throws InvalidConfigException
* @throws \yii\db\Exception
*/
public function order($newPosition, $foreignKeyName = null, $where = []) {
/**
* @var $owner ActiveRecord
*/
$owner = $this->owner;
if ($foreignKeyName) { // restrict order to records with the same foreign key value
if (! isset($this->orderAttribute[$foreignKeyName]))
throw new InvalidConfigException(get_called_class() . "::orderAttribute[$foreignKeyName] is not set.");
$orderAttr = $this->orderAttribute[$foreignKeyName];
$where[$foreignKeyName] = $owner->getAttribute($foreignKeyName);
}
else { // order all records
$orderAttr = null;
if (is_array($this->orderAttribute)) {
foreach ($this->orderAttribute as $k => $v) { // search for non-associative array entry
if (is_integer($k)) {
$orderAttr = $v;
break;
}
}
}
else $orderAttr = $this->orderAttribute;
if (! $orderAttr)
throw new InvalidConfigException('No default order attribute found in '. get_called_class());
}
$oldPosition = $owner->getAttribute($orderAttr);
/**
* @var $trans Transaction
*/
$trans = $owner->db->beginTransaction();
try {
if ($newPosition > $oldPosition) {
// new position greater than old position,
// so all positions from old position + 1 up to and including new position should decrement
$owner->updateAllCounters([$orderAttr => -1],[
'and',
$where,
['between', $orderAttr, $oldPosition + 1, $newPosition]
]);
}
else {
// new position smaller than or equal to old position,
// so all positions from new position up to and including old position - 1 should increment
$owner->updateAllCounters([$orderAttr => 1],[
'and',
$where,
['between', $orderAttr, $newPosition, $oldPosition - 1]
]);
}
$owner->updateAttributes([$orderAttr => $newPosition]);
$trans->commit();
} catch (Exception $e) {
$trans->rollBack();
}
}
}