/
SequenceBehavior.php
562 lines (497 loc) · 18.8 KB
/
SequenceBehavior.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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
<?php
declare(strict_types=1);
namespace ADmad\Sequence\Model\Behavior;
use ArrayObject;
use Cake\Database\Expression\IdentifierExpression;
use Cake\Database\Expression\QueryExpression;
use Cake\Datasource\EntityInterface;
use Cake\Event\EventInterface;
use Cake\ORM\Behavior;
use Cake\ORM\Query;
/**
* SequenceBehavior maintains a contiguous sequence of integers (starting at 1
* or other configurable integer) in a selected column, such as `position`, for all
* records in a table, or groups of records identified by one or more
* 'scope' fields, when adding, editing (including moving groups) or deleting
* records.
*
* Consider the following simple example with no groups:
* Record Position
* A 1
* B 2
* C 3
* D 4
* E 5
* F 6
* G 7
* - Save
* - If adding new record
* - If order not specified e.g. Record H added:
* Inserts H at end of list i.e. highest order + 1
* - If order specified e.g. Record H added at position 3:
* Inserts at specified order
* Increments order of all other records whose order >= order of
* inserted record i.e. D, E, F & G get incremented
* - If editing existing record:
* - If order not specified and scope not specified, or same
* No Action
* - If order not specified but scope specified and different:
* Decrement order of all records whose order > old order in the old
* scope, and change order to highest order of new scopes + 1
* - If order specified:
* - If new order < old order e.g. record E moves from 4 to 2
* Increments order of all other records whose order > new order and
* order < old order i.e. order of C & D get incremented
* - If new order > old order e.g. record C moves from 2 to 4
* Decrements order of all other records whose order > old order and
* <= new order i.e. order of D & E get decremented
* - If new order == old order
* No action
* - Delete
* Decrement order of all records whose order > order of deleted record
*
* Inspired by Neil Crooke's Sequence behavior for CakePHP 1.3. Above description
* has been "borrowed" from it :).
*
* @copyright 2015-Present ADmad
* @link https://github.com/ADmad/cakephp-sequence
* @license MIT License - http://www.opensource.org/licenses/mit-license.php
*/
class SequenceBehavior extends Behavior
{
/**
* Default settings.
*
* @var array
*/
protected $_defaultConfig = [
'sequenceField' => 'position',
'scope' => [],
'startAt' => 1,
];
/**
* Old values for the entity being deleted
*
* @var array|null
*/
protected $_oldValues;
/**
* Normalize config options.
*
* @param array $config Configuration options include:
* - sequenceField : The field name that stores the sequence number.
* Defaults is "position".
* - scope : Array of field names that identify a single group of records
* that need to form a contiguous sequence.
* Default is empty array, i.e. no scope fields.
* - startAt : You can start your sequence numbers at 0 or 1 or any other.
* Defaults is 1.
* @return void
*/
public function initialize(array $config): void
{
if (!$this->_config['scope']) {
return;
}
if (is_string($this->_config['scope'])) {
$this->_config['scope'] = [$this->_config['scope']];
}
}
/**
* Adds order value if not already set in query.
*
* @param \Cake\Event\EventInterface $event The beforeFind event that was fired.
* @param \Cake\ORM\Query $query The query object.
* @param \ArrayObject $options The options passed to the find method.
* @return void
*/
public function beforeFind(EventInterface $event, Query $query, ArrayObject $options): void
{
if (!$query->clause('order')) {
$query->order([$this->_table->aliasField($this->_config['sequenceField']) => 'ASC']);
}
}
/**
* Sets entity's order and updates order of other records when necessary.
*
* @param \Cake\Event\EventInterface $event The beforeSave event that was fired.
* @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved.
* @param \ArrayObject $options The options passed to the save method.
* @return void
*/
public function beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options): void
{
$config = $this->getConfig();
$newOrder = null;
$newScope = $this->_getScope($entity);
if ($newScope === false) {
return;
}
$orderField = $config['sequenceField'];
$newOrder = $entity->get($orderField);
// Adding
if ($entity->isNew()) {
// Order not specified
if ($newOrder === null) {
// Insert at end of list
$entity->set($orderField, $this->_getHighestOrder($newScope) + 1);
// Order specified
} else {
// Increment order of records it's inserted before
$this->_sync(
[$orderField => $this->_getUpdateExpression('+')],
[$orderField . ' >=' => $newOrder],
$newScope
);
}
// Editing
} else {
// No action if no new order or scope specified
if ($newOrder === null && !$newScope) {
return;
}
[$oldOrder, $oldScope] = $this->_getOldValues($entity);
// No action if new and old scope and order same
if (
$newOrder == $oldOrder &&
$newScope == $oldScope
) {
return;
}
// If changing scope
if ($newScope && $newScope != $oldScope) {
// Decrement records in old scope with higher order than moved record old order
$this->_sync(
[$orderField => $this->_getUpdateExpression('-')],
[$orderField . ' >' => $oldOrder],
$oldScope
);
// Order not specified
if ($newOrder === null) {
// Insert at end of new scope
$entity->set(
$orderField,
$this->_getHighestOrder($newScope) + 1
);
// Order specified
} else {
// Increment records in new scope with higher order than moved record new order
$this->_sync(
[$orderField => $this->_getUpdateExpression('+')],
[$orderField . ' >=' => $newOrder],
$newScope
);
}
// Same scope
} else {
// If moving up
if ($newOrder < $oldOrder) {
// Increment order of those in between
$this->_sync(
[$orderField => $this->_getUpdateExpression('+')],
[
$orderField . ' >=' => $newOrder,
$orderField . ' <' => $oldOrder,
],
$newScope
);
// Moving down
} else {
// Decrement order of those in between
$this->_sync(
[$orderField => $this->_getUpdateExpression('-')],
[
$orderField . ' >' => $oldOrder,
$orderField . ' <=' => $newOrder,
],
$newScope
);
}
}
}
}
/**
* When you delete a record from a set, you need to decrement the order of all
* records that were after it in the set.
*
* This hook just stores all required values from the entity. Actual order
* updation is done in "afterDelete" hook.
*
* @param \Cake\Event\EventInterface $event The beforeDelete event that was fired.
* @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved.
* @return void
*/
public function beforeDelete(EventInterface $event, EntityInterface $entity): void
{
$this->_oldValues = $this->_getOldValues($entity);
}
/**
* When you delete a record from a set, you need to decrement the order of all
* records that were after it in the set.
*
* @param \Cake\Event\EventInterface $event The beforeDelete event that was fired.
* @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved.
* @return void
*/
public function afterDelete(EventInterface $event, EntityInterface $entity)
{
if (!$this->_oldValues) {
return;
}
$orderField = $this->_config['sequenceField'];
[$order, $scope] = $this->_oldValues;
$this->_sync(
[$orderField => $this->_getUpdateExpression('-')],
[$orderField . ' >' => $order],
$scope
);
$this->_oldValues = null;
}
/**
* Decrease the position of the entity on the list
*
* If a "higher" entity exists, this will also swap positions with it
*
* @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved.
* @return bool
*/
public function moveUp(EntityInterface $entity)
{
return $this->_movePosition($entity, '-');
}
/**
* Increase the position of the entity on the list
*
* If a "lower" entity exists, this will also swap positions with it
*
* @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved.
* @return bool
*/
public function moveDown(EntityInterface $entity)
{
return $this->_movePosition($entity, '+');
}
/**
* Change the position of the entity on the list by a single position
*
* If an entity that conflicts with the new position already exists, this
* will also swap positions with it
*
* @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved.
* @param string $direction Whether to increment or decrement the field.
* @return bool
*/
protected function _movePosition(EntityInterface $entity, string $direction = '+'): bool
{
if ($entity->isNew()) {
return false;
}
$scope = $this->_getScope($entity);
if ($scope === false) {
return false;
}
$config = $this->getConfig();
$table = $this->_table;
$table->removeBehavior('Sequence');
$return = $table->getConnection()->transactional(
function ($connection) use ($table, $entity, $config, $scope, $direction) {
$orderField = $config['sequenceField'];
// Nothing to do if trying to move up entity already at first position
if ($direction === '-' && $entity->get($orderField) === $config['startAt']) {
return true;
}
$oldOrder = $entity->get($orderField);
$newOrder = $entity->get($orderField) - 1;
if ($direction === '+') {
$newOrder = $entity->get($orderField) + 1;
}
/** @var \Cake\Datasource\EntityInterface|null $previousEntity */
$previousEntity = $table->find()
->where(array_merge($scope, [$orderField => $newOrder]))
->first();
if ($previousEntity === null) {
// Nothing to do if trying to move down entity already at last position
return true;
} elseif ($direction === '+') {
$previousEntity->set($orderField, $oldOrder);
if (!$table->save($previousEntity, ['atomic' => false, 'checkRules' => false])) {
return false;
}
}
$entity->set($orderField, $newOrder);
return $table->save($entity, ['atomic' => false, 'checkRules' => false]);
}
);
$table->addBehavior('ADmad/Sequence.Sequence', $config);
return (bool)$return;
}
/**
* Set order for list of records provided.
*
* Records can be provided as array of entities or array of associative
* arrays like `[['id' => 1], ['id' => 2]]` or array of primary key values
* like `[1, 2]`.
*
* @param array $records Records.
* @return bool
*/
public function setOrder(array $records): bool
{
$config = $this->getConfig();
$table = $this->_table;
$table->removeBehavior('Sequence');
$return = $table->getConnection()->transactional(
function ($connection) use ($table, $records) {
$order = $this->_config['startAt'];
$field = $this->_config['sequenceField'];
/** @var string $primaryKeyField */
$primaryKeyField = $table->getPrimaryKey();
foreach ($records as $record) {
if (is_scalar($record)) {
$record = [$primaryKeyField => $record];
}
if (is_array($record)) {
$record = $table->newEntity($record, [
'fields' => array_keys($record),
'validate' => false,
'accessibleFields' => [
$primaryKeyField => true,
],
]);
$record->setNew(false);
$record->setDirty($primaryKeyField, false);
}
$record->setAccess($field, true);
$record->set($field, $order++);
$r = $table->save(
$record,
['atomic' => false, 'checkRules' => false]
);
if ($r === false) {
return false;
}
}
return true;
}
);
$table->addBehavior('ADmad/Sequence.Sequence', $config);
return $return;
}
/**
* Get old order and scope values.
*
* @param \Cake\Datasource\EntityInterface $entity Entity.
* @return array
*/
protected function _getOldValues(EntityInterface $entity): array
{
$config = $this->getConfig();
$fields = array_merge($config['scope'], [$config['sequenceField']]);
$values = [];
foreach ($fields as $field) {
if ($entity->isDirty($field)) {
$values[$field] = $entity->getOriginal($field);
} elseif ($entity->has($field)) {
$values[$field] = $entity->get($field);
}
}
if (count($fields) != count($values)) {
/** @psalm-suppress PossiblyInvalidArgument */
$primaryKey = $entity->get($this->_table->getPrimaryKey());
$entity = $this->_table->get($primaryKey, ['fields' => $fields]);
$values = $entity->extract($fields);
}
$order = $values[$config['sequenceField']];
unset($values[$config['sequenceField']]);
foreach ($values as $field => $value) {
if (is_null($value)) {
$values[$field . ' IS'] = $value;
unset($values[$field]);
}
}
return [$order, $values];
}
/**
* Get scope values.
*
* @param \Cake\Datasource\EntityInterface $entity Entity.
* @return array|false
*/
protected function _getScope(EntityInterface $entity)
{
$scope = [];
$config = $this->getConfig();
// If scope are specified and data for all scope fields is not
// provided we cannot calculate new order
if ($config['scope']) {
$scope = $entity->extract($config['scope']);
if (count($scope) !== count($config['scope'])) {
return false;
}
// Modify where clauses when NULL values are used
foreach ($scope as $field => $value) {
if (is_null($value)) {
$scope[$field . ' IS'] = $value;
unset($scope[$field]);
}
}
}
return $scope;
}
/**
* Returns the current highest order of all records in the set. When a new
* record is added to the set, it is added at the current highest order, plus
* one.
*
* @param array $scope Array with scope field => scope values, used for conditions.
* @return int Value of order field of last record in set
*/
protected function _getHighestOrder(array $scope = []): int
{
$orderField = $this->_config['sequenceField'];
// Find the last record in the set
$last = $this->_table->find()
->select([$orderField])
->where($scope)
->order([$orderField => 'DESC'])
->limit(1)
->enableHydration(false)
->first();
// If there is a last record (i.e. any) in the set, return the it's order
if ($last) {
return $last[$orderField];
}
// If there isn't any records in the set, return the start number minus 1
return (int)$this->_config['startAt'] - 1;
}
/**
* Auxiliary function used to alter the value of order fields by a certain
* amount that match the passed conditions.
*
* @param array $fields Fields to update.
* @param array $conditions Conditions for matching rows.
* @param array $scope Grouping scope that will be added to coditions.
* @return int Count of rows updated.
*/
protected function _sync(array $fields, array $conditions, ?array $scope = null): int
{
if ($scope) {
$conditions = array_merge($conditions, $scope);
}
return $this->_table->updateAll($fields, $conditions);
}
/**
* Returns the update expression for the order field.
*
* @param string $direction Whether to increment or decrement the field.
* @return \Cake\Database\Expression\QueryExpression QueryExpression to modify the order field
*/
protected function _getUpdateExpression(string $direction = '+'): QueryExpression
{
$field = $this->_config['sequenceField'];
return $this->_table->query()->newExpr()
->add(new IdentifierExpression($field))
->add('1')
->setConjunction($direction);
}
}