-
Notifications
You must be signed in to change notification settings - Fork 129
/
Copy pathNestedSetsBehavior.php
673 lines (578 loc) · 22.2 KB
/
NestedSetsBehavior.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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
<?php
/**
* @link https://github.com/creocoder/yii2-nested-sets
* @copyright Copyright (c) 2015 Alexander Kochetov
* @license http://opensource.org/licenses/BSD-3-Clause
*/
namespace creocoder\nestedsets;
use yii\base\Behavior;
use yii\base\NotSupportedException;
use yii\db\ActiveRecord;
use yii\db\Exception;
use yii\db\Expression;
/**
* NestedSetsBehavior
*
* @property ActiveRecord $owner
*
* @author Alexander Kochetov <[email protected]>
*/
class NestedSetsBehavior extends Behavior
{
const OPERATION_MAKE_ROOT = 'makeRoot';
const OPERATION_PREPEND_TO = 'prependTo';
const OPERATION_APPEND_TO = 'appendTo';
const OPERATION_INSERT_BEFORE = 'insertBefore';
const OPERATION_INSERT_AFTER = 'insertAfter';
const OPERATION_DELETE_WITH_CHILDREN = 'deleteWithChildren';
/**
* @var string|false
*/
public $treeAttribute = false;
/**
* @var string
*/
public $leftAttribute = 'lft';
/**
* @var string
*/
public $rightAttribute = 'rgt';
/**
* @var string
*/
public $depthAttribute = 'depth';
/**
* @var string|null
*/
protected $operation;
/**
* @var ActiveRecord|null
*/
protected $node;
/**
* @inheritdoc
*/
public function events()
{
return [
ActiveRecord::EVENT_BEFORE_INSERT => 'beforeInsert',
ActiveRecord::EVENT_AFTER_INSERT => 'afterInsert',
ActiveRecord::EVENT_BEFORE_UPDATE => 'beforeUpdate',
ActiveRecord::EVENT_AFTER_UPDATE => 'afterUpdate',
ActiveRecord::EVENT_BEFORE_DELETE => 'beforeDelete',
ActiveRecord::EVENT_AFTER_DELETE => 'afterDelete',
];
}
/**
* Creates the root node if the active record is new or moves it
* as the root node.
* @return ActiveRecord
*/
public function makeRoot()
{
$this->operation = self::OPERATION_MAKE_ROOT;
return $this->owner;
}
/**
* Creates a node as the first child of the target node if the active
* record is new or moves it as the first child of the target node.
* @param $node
* @return ActiveRecord
*/
public function prependTo($node)
{
$this->operation = self::OPERATION_PREPEND_TO;
$this->node = $node;
return $this->owner;
}
/**
* Creates a node as the last child of the target node if the active
* record is new or moves it as the last child of the target node.
* @param $node
* @return ActiveRecord
*/
public function appendTo($node)
{
$this->operation = self::OPERATION_APPEND_TO;
$this->node = $node;
return $this->owner;
}
/**
* Creates a node as the previous sibling of the target node if the active
* record is new or moves it as the previous sibling of the target node.
* @param $node
* @return ActiveRecord
*/
public function insertBefore($node)
{
$this->operation = self::OPERATION_INSERT_BEFORE;
$this->node = $node;
return $this->owner;
}
/**
* Creates a node as the next sibling of the target node if the active
* record is new or moves it as the next sibling of the target node.
* @param $node
* @return ActiveRecord
*/
public function insertAfter($node)
{
$this->operation = self::OPERATION_INSERT_AFTER;
$this->node = $node;
return $this->owner;
}
/**
* Deletes a node and its children.
* @return integer|false the number of rows deleted or false if
* the deletion is unsuccessful for some reason.
* @throws \Exception
*/
public function deleteWithChildren()
{
$this->operation = self::OPERATION_DELETE_WITH_CHILDREN;
if (!$this->owner->isTransactional(ActiveRecord::OP_DELETE)) {
return $this->deleteWithChildrenInternal();
}
$transaction = $this->owner->getDb()->beginTransaction();
try {
$result = $this->deleteWithChildrenInternal();
if ($result === false) {
$transaction->rollBack();
} else {
$transaction->commit();
}
return $result;
} catch (\Exception $e) {
$transaction->rollBack();
throw $e;
}
}
/**
* @return integer|false the number of rows deleted or false if
* the deletion is unsuccessful for some reason.
*/
protected function deleteWithChildrenInternal()
{
if (!$this->owner->beforeDelete()) {
return false;
}
$condition = [
'and',
['>=', $this->leftAttribute, $this->owner->getAttribute($this->leftAttribute)],
['<=', $this->rightAttribute, $this->owner->getAttribute($this->rightAttribute)]
];
$this->applyTreeAttributeCondition($condition);
$result = $this->owner->deleteAll($condition);
$this->owner->setOldAttributes(null);
$this->owner->afterDelete();
return $result;
}
/**
* Gets the parents of the node.
* @param integer|null $depth the depth
* @return \yii\db\ActiveQuery
*/
public function parents($depth = null)
{
$condition = [
'and',
['<', $this->leftAttribute, $this->owner->getAttribute($this->leftAttribute)],
['>', $this->rightAttribute, $this->owner->getAttribute($this->rightAttribute)],
];
if ($depth !== null) {
$condition[] = ['>=', $this->depthAttribute, $this->owner->getAttribute($this->depthAttribute) - $depth];
}
$this->applyTreeAttributeCondition($condition);
return $this->owner->find()->andWhere($condition)->addOrderBy([$this->leftAttribute => SORT_ASC]);
}
/**
* Gets the children of the node.
* @param integer|null $depth the depth
* @return \yii\db\ActiveQuery
*/
public function children($depth = null)
{
$condition = [
'and',
['>', $this->leftAttribute, $this->owner->getAttribute($this->leftAttribute)],
['<', $this->rightAttribute, $this->owner->getAttribute($this->rightAttribute)],
];
if ($depth !== null) {
$condition[] = ['<=', $this->depthAttribute, $this->owner->getAttribute($this->depthAttribute) + $depth];
}
$this->applyTreeAttributeCondition($condition);
return $this->owner->find()->andWhere($condition)->addOrderBy([$this->leftAttribute => SORT_ASC]);
}
/**
* Gets the leaves of the node.
* @return \yii\db\ActiveQuery
*/
public function leaves()
{
$condition = [
'and',
['>', $this->leftAttribute, $this->owner->getAttribute($this->leftAttribute)],
['<', $this->rightAttribute, $this->owner->getAttribute($this->rightAttribute)],
[$this->rightAttribute => new Expression($this->owner->getDb()->quoteColumnName($this->leftAttribute) . '+ 1')],
];
$this->applyTreeAttributeCondition($condition);
return $this->owner->find()->andWhere($condition)->addOrderBy([$this->leftAttribute => SORT_ASC]);
}
/**
* Gets the previous sibling of the node.
* @return \yii\db\ActiveQuery
*/
public function prev()
{
$condition = [$this->rightAttribute => $this->owner->getAttribute($this->leftAttribute) - 1];
$this->applyTreeAttributeCondition($condition);
return $this->owner->find()->andWhere($condition);
}
/**
* Gets the next sibling of the node.
* @return \yii\db\ActiveQuery
*/
public function next()
{
$condition = [$this->leftAttribute => $this->owner->getAttribute($this->rightAttribute) + 1];
$this->applyTreeAttributeCondition($condition);
return $this->owner->find()->andWhere($condition);
}
/**
* Determines whether the node is root.
* @return boolean whether the node is root
*/
public function isRoot()
{
return $this->owner->getAttribute($this->leftAttribute) == 1;
}
/**
* Determines whether the node is child of the parent node.
* @param ActiveRecord $node the parent node
* @return boolean whether the node is child of the parent node
*/
public function isChildOf($node)
{
$result = $this->owner->getAttribute($this->leftAttribute) > $node->getAttribute($this->leftAttribute)
&& $this->owner->getAttribute($this->rightAttribute) < $node->getAttribute($this->rightAttribute);
if ($result && $this->treeAttribute !== false) {
$result = $this->owner->getAttribute($this->treeAttribute) === $node->getAttribute($this->treeAttribute);
}
return $result;
}
/**
* Determines whether the node is leaf.
* @return boolean whether the node is leaf
*/
public function isLeaf()
{
return $this->owner->getAttribute($this->rightAttribute) - $this->owner->getAttribute($this->leftAttribute) === 1;
}
/**
* @throws NotSupportedException
*/
public function beforeInsert()
{
if ($this->node !== null && !$this->node->getIsNewRecord()) {
$this->node->refresh();
}
switch ($this->operation) {
case self::OPERATION_MAKE_ROOT:
$this->beforeInsertRootNode();
break;
case self::OPERATION_PREPEND_TO:
$this->beforeInsertNode($this->node->getAttribute($this->leftAttribute) + 1, 1);
break;
case self::OPERATION_APPEND_TO:
$this->beforeInsertNode($this->node->getAttribute($this->rightAttribute), 1);
break;
case self::OPERATION_INSERT_BEFORE:
$this->beforeInsertNode($this->node->getAttribute($this->leftAttribute), 0);
break;
case self::OPERATION_INSERT_AFTER:
$this->beforeInsertNode($this->node->getAttribute($this->rightAttribute) + 1, 0);
break;
default:
throw new NotSupportedException('Method "'. get_class($this->owner) . '::insert" is not supported for inserting new nodes.');
}
}
/**
* @throws Exception
*/
protected function beforeInsertRootNode()
{
if ($this->treeAttribute === false && $this->owner->find()->roots()->exists()) {
throw new Exception('Can not create more than one root when "treeAttribute" is false.');
}
$this->owner->setAttribute($this->leftAttribute, 1);
$this->owner->setAttribute($this->rightAttribute, 2);
$this->owner->setAttribute($this->depthAttribute, 0);
}
/**
* @param integer $value
* @param integer $depth
* @throws Exception
*/
protected function beforeInsertNode($value, $depth)
{
if ($this->node->getIsNewRecord()) {
throw new Exception('Can not create a node when the target node is new record.');
}
if ($depth === 0 && $this->node->isRoot()) {
throw new Exception('Can not create a node when the target node is root.');
}
$this->owner->setAttribute($this->leftAttribute, $value);
$this->owner->setAttribute($this->rightAttribute, $value + 1);
$this->owner->setAttribute($this->depthAttribute, $this->node->getAttribute($this->depthAttribute) + $depth);
if ($this->treeAttribute !== false) {
$this->owner->setAttribute($this->treeAttribute, $this->node->getAttribute($this->treeAttribute));
}
$this->shiftLeftRightAttribute($value, 2);
}
/**
* @throws Exception
*/
public function afterInsert()
{
if ($this->operation === self::OPERATION_MAKE_ROOT && $this->treeAttribute !== false) {
$this->owner->setAttribute($this->treeAttribute, $this->owner->getPrimaryKey());
$primaryKey = $this->owner->primaryKey();
if (!isset($primaryKey[0])) {
throw new Exception('"' . get_class($this->owner) . '" must have a primary key.');
}
$this->owner->updateAll(
[$this->treeAttribute => $this->owner->getAttribute($this->treeAttribute)],
[$primaryKey[0] => $this->owner->getAttribute($this->treeAttribute)]
);
}
$this->operation = null;
$this->node = null;
}
/**
* @throws Exception
*/
public function beforeUpdate()
{
if ($this->node !== null && !$this->node->getIsNewRecord()) {
$this->node->refresh();
}
switch ($this->operation) {
case self::OPERATION_MAKE_ROOT:
if ($this->treeAttribute === false) {
throw new Exception('Can not move a node as the root when "treeAttribute" is false.');
}
if ($this->owner->isRoot()) {
throw new Exception('Can not move the root node as the root.');
}
break;
case self::OPERATION_INSERT_BEFORE:
case self::OPERATION_INSERT_AFTER:
if ($this->node->isRoot()) {
throw new Exception('Can not move a node when the target node is root.');
}
case self::OPERATION_PREPEND_TO:
case self::OPERATION_APPEND_TO:
if ($this->node->getIsNewRecord()) {
throw new Exception('Can not move a node when the target node is new record.');
}
if ($this->owner->equals($this->node)) {
throw new Exception('Can not move a node when the target node is same.');
}
if ($this->node->isChildOf($this->owner)) {
throw new Exception('Can not move a node when the target node is child.');
}
}
}
/**
* @return void
*/
public function afterUpdate()
{
switch ($this->operation) {
case self::OPERATION_MAKE_ROOT:
$this->moveNodeAsRoot();
break;
case self::OPERATION_PREPEND_TO:
$this->moveNode($this->node->getAttribute($this->leftAttribute) + 1, 1);
break;
case self::OPERATION_APPEND_TO:
$this->moveNode($this->node->getAttribute($this->rightAttribute), 1);
break;
case self::OPERATION_INSERT_BEFORE:
$this->moveNode($this->node->getAttribute($this->leftAttribute), 0);
break;
case self::OPERATION_INSERT_AFTER:
$this->moveNode($this->node->getAttribute($this->rightAttribute) + 1, 0);
break;
default:
return;
}
$this->operation = null;
$this->node = null;
}
/**
* @return void
*/
protected function moveNodeAsRoot()
{
$db = $this->owner->getDb();
$leftValue = $this->owner->getAttribute($this->leftAttribute);
$rightValue = $this->owner->getAttribute($this->rightAttribute);
$depthValue = $this->owner->getAttribute($this->depthAttribute);
$treeValue = $this->owner->getAttribute($this->treeAttribute);
$leftAttribute = $db->quoteColumnName($this->leftAttribute);
$rightAttribute = $db->quoteColumnName($this->rightAttribute);
$depthAttribute = $db->quoteColumnName($this->depthAttribute);
$this->owner->updateAll(
[
$this->leftAttribute => new Expression($leftAttribute . sprintf('%+d', 1 - $leftValue)),
$this->rightAttribute => new Expression($rightAttribute . sprintf('%+d', 1 - $leftValue)),
$this->depthAttribute => new Expression($depthAttribute . sprintf('%+d', -$depthValue)),
$this->treeAttribute => $this->owner->getPrimaryKey(),
],
[
'and',
['>=', $this->leftAttribute, $leftValue],
['<=', $this->rightAttribute, $rightValue],
[$this->treeAttribute => $treeValue]
]
);
$this->shiftLeftRightAttribute($rightValue + 1, $leftValue - $rightValue - 1);
}
/**
* @param integer $value
* @param integer $depth
*/
protected function moveNode($value, $depth)
{
$db = $this->owner->getDb();
$leftValue = $this->owner->getAttribute($this->leftAttribute);
$rightValue = $this->owner->getAttribute($this->rightAttribute);
$depthValue = $this->owner->getAttribute($this->depthAttribute);
$depthAttribute = $db->quoteColumnName($this->depthAttribute);
$depth = $this->node->getAttribute($this->depthAttribute) - $depthValue + $depth;
if ($this->treeAttribute === false
|| $this->owner->getAttribute($this->treeAttribute) === $this->node->getAttribute($this->treeAttribute)) {
$delta = $rightValue - $leftValue + 1;
$this->shiftLeftRightAttribute($value, $delta);
if ($leftValue >= $value) {
$leftValue += $delta;
$rightValue += $delta;
}
$condition = ['and', ['>=', $this->leftAttribute, $leftValue], ['<=', $this->rightAttribute, $rightValue]];
$this->applyTreeAttributeCondition($condition);
$this->owner->updateAll(
[$this->depthAttribute => new Expression($depthAttribute . sprintf('%+d', $depth))],
$condition
);
foreach ([$this->leftAttribute, $this->rightAttribute] as $attribute) {
$condition = ['and', ['>=', $attribute, $leftValue], ['<=', $attribute, $rightValue]];
$this->applyTreeAttributeCondition($condition);
$this->owner->updateAll(
[$attribute => new Expression($db->quoteColumnName($attribute) . sprintf('%+d', $value - $leftValue))],
$condition
);
}
$this->shiftLeftRightAttribute($rightValue + 1, -$delta);
} else {
$leftAttribute = $db->quoteColumnName($this->leftAttribute);
$rightAttribute = $db->quoteColumnName($this->rightAttribute);
$nodeRootValue = $this->node->getAttribute($this->treeAttribute);
foreach ([$this->leftAttribute, $this->rightAttribute] as $attribute) {
$this->owner->updateAll(
[$attribute => new Expression($db->quoteColumnName($attribute) . sprintf('%+d', $rightValue - $leftValue + 1))],
['and', ['>=', $attribute, $value], [$this->treeAttribute => $nodeRootValue]]
);
}
$delta = $value - $leftValue;
$this->owner->updateAll(
[
$this->leftAttribute => new Expression($leftAttribute . sprintf('%+d', $delta)),
$this->rightAttribute => new Expression($rightAttribute . sprintf('%+d', $delta)),
$this->depthAttribute => new Expression($depthAttribute . sprintf('%+d', $depth)),
$this->treeAttribute => $nodeRootValue,
],
[
'and',
['>=', $this->leftAttribute, $leftValue],
['<=', $this->rightAttribute, $rightValue],
[$this->treeAttribute => $this->owner->getAttribute($this->treeAttribute)],
]
);
$this->shiftLeftRightAttribute($rightValue + 1, $leftValue - $rightValue - 1);
}
}
/**
* @throws Exception
* @throws NotSupportedException
*/
public function beforeDelete()
{
if ($this->owner->getIsNewRecord()) {
throw new Exception('Can not delete a node when it is new record.');
}
if ($this->owner->isRoot() && $this->operation !== self::OPERATION_DELETE_WITH_CHILDREN) {
throw new NotSupportedException('Method "'. get_class($this->owner) . '::delete" is not supported for deleting root nodes.');
}
$this->owner->refresh();
}
/**
* @return void
*/
public function afterDelete()
{
$leftValue = $this->owner->getAttribute($this->leftAttribute);
$rightValue = $this->owner->getAttribute($this->rightAttribute);
if ($this->owner->isLeaf() || $this->operation === self::OPERATION_DELETE_WITH_CHILDREN) {
$this->shiftLeftRightAttribute($rightValue + 1, $leftValue - $rightValue - 1);
} else {
$condition = [
'and',
['>=', $this->leftAttribute, $this->owner->getAttribute($this->leftAttribute)],
['<=', $this->rightAttribute, $this->owner->getAttribute($this->rightAttribute)]
];
$this->applyTreeAttributeCondition($condition);
$db = $this->owner->getDb();
$this->owner->updateAll(
[
$this->leftAttribute => new Expression($db->quoteColumnName($this->leftAttribute) . sprintf('%+d', -1)),
$this->rightAttribute => new Expression($db->quoteColumnName($this->rightAttribute) . sprintf('%+d', -1)),
$this->depthAttribute => new Expression($db->quoteColumnName($this->depthAttribute) . sprintf('%+d', -1)),
],
$condition
);
$this->shiftLeftRightAttribute($rightValue + 1, -2);
}
$this->operation = null;
$this->node = null;
}
/**
* @param integer $value
* @param integer $delta
*/
protected function shiftLeftRightAttribute($value, $delta)
{
$db = $this->owner->getDb();
foreach ([$this->leftAttribute, $this->rightAttribute] as $attribute) {
$condition = ['>=', $attribute, $value];
$this->applyTreeAttributeCondition($condition);
$this->owner->updateAll(
[$attribute => new Expression($db->quoteColumnName($attribute) . sprintf('%+d', $delta))],
$condition
);
}
}
/**
* @param array $condition
*/
protected function applyTreeAttributeCondition(&$condition)
{
if ($this->treeAttribute !== false) {
$condition = [
'and',
$condition,
[$this->treeAttribute => $this->owner->getAttribute($this->treeAttribute)]
];
}
}
}