-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNestedSetsBehavior.php
More file actions
1396 lines (1288 loc) · 57.1 KB
/
NestedSetsBehavior.php
File metadata and controls
1396 lines (1288 loc) · 57.1 KB
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
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
namespace yii2\extensions\nestedsets;
use LogicException;
use yii\base\{Behavior, NotSupportedException};
use yii\db\{ActiveQuery, ActiveRecord, Exception, Expression};
/**
* Nested set behavior for managing hierarchical data in {@see ActiveRecord} models.
*
* Provides a set of methods and properties to implement the nested sets pattern in Yii {@see ActiveRecord} models,
* enabling efficient management of hierarchical data structures such as trees and categories.
*
* This behavior allows nodes to be inserted, moved, or deleted within the tree, and supports querying for parents,
* children, leaves, and siblings.
*
* The behavior manages the left, right, and depth attributes of each node, and can optionally support multiple trees
* using a tree attribute.
*
* It integrates with a Yii event system and can be attached to any {@see ActiveRecord} model.
*
* Key features.
* - Compatible with Yii {@see ActiveRecord} and event system.
* - Delete nodes with or without their children.
* - Insert nodes as root, before/after, or as children of other nodes.
* - Move nodes within the tree while maintaining integrity.
* - Query for parents, children, leaves, previous and next siblings.
* - Supports custom attribute names for left, right, depth, and tree columns.
*
* @phpstan-template T of ActiveRecord
*
* @phpstan-extends Behavior<T>
*
* @property int $depth
* @property int $lft
* @property int $rgt
*
* @copyright Copyright (C) 2023 Terabytesoftw.
* @license https://opensource.org/license/bsd-3-clause BSD 3-Clause License.
*/
class NestedSetsBehavior extends Behavior
{
/**
* Operation constant for appending the current node as the last child of a target node.
*/
public const OPERATION_APPEND_TO = 'appendTo';
/**
* Operation constant for deleting a node along with all its descendant nodes.
*/
public const OPERATION_DELETE_WITH_CHILDREN = 'deleteWithChildren';
/**
* Operation constant for inserting the current node immediately after a target node at the same level.
*/
public const OPERATION_INSERT_AFTER = 'insertAfter';
/**
* Operation constant for inserting the current node immediately before a target node at the same level.
*/
public const OPERATION_INSERT_BEFORE = 'insertBefore';
/**
* Operation constant for making the current node a root node in the tree.
*/
public const OPERATION_MAKE_ROOT = 'makeRoot';
/**
* Operation constant for prepending the current node as the first child of a target node.
*/
public const OPERATION_PREPEND_TO = 'prependTo';
/**
* Holds the reference to the current node involved in a nested set operation.
*
* Stores the {@see ActiveRecord} instance representing the node being manipulated by the behavior during operations
* such as insertion, movement, or deletion within the tree structure.
*
* @template T of NestedSetsBehavior
*
* @phpstan-var ActiveRecord<T>|null
*/
protected ActiveRecord|null $node = null;
/**
* Stores the current operation being performed on the node.
*
* Holds the operation type as a string identifier, such as 'appendTo', 'deleteWithChildren', or other defined
* operation constants.
*/
protected string|null $operation = null;
/**
* Name of the attribute that stores the depth (level) of the node in the tree.
*
* @phpstan-var 'depth' attribute name.
*/
public string $depthAttribute = 'depth';
/**
* Name of the attribute that stores the left boundary value of the node in the nested set tree.
*
* @phpstan-var 'lft' attribute name.
*/
public string $leftAttribute = 'lft';
/**
* Name of the attribute that stores the right boundary value of the node in the nested set tree.
*
* @phpstan-var 'rgt' attribute name.
*/
public string $rightAttribute = 'rgt';
/**
* Name of the attribute that stores the tree identifier for supporting multiple trees.
*/
public string|false $treeAttribute = false;
/**
* Handles post-deletion updates for the nested set structure.
*
* Updates left, right, and depth attributes of affected nodes after a node is deleted, ensuring the tree remains
* consistent.
* - If the node is deleted with its children or is a leaf, shifts the left/right values accordingly.
* - Otherwise, updates the subtree and shifts attributes for remaining nodes.
*
* This method is automatically triggered after a node deletion event and is essential for maintaining the integrity
* of the nested set hierarchy.
*
* Usage example:
* ```php
* // `afterDelete()` is called automatically to update the tree structure
* $model->delete();
* ``
*/
public function afterDelete(): void
{
$leftValue = $this->getOwner()->getAttribute($this->leftAttribute);
$rightValue = $this->getOwner()->getAttribute($this->rightAttribute);
if ($this->operation === self::OPERATION_DELETE_WITH_CHILDREN || $this->getOwner()->isLeaf()) {
$this->shiftLeftRightAttribute($rightValue, $leftValue - $rightValue - 1);
} else {
$condition = [
'and',
[
'>=',
$this->leftAttribute,
$this->getOwner()->getAttribute($this->leftAttribute),
],
[
'<=',
$this->rightAttribute,
$this->getOwner()->getAttribute($this->rightAttribute),
],
];
$this->applyTreeAttributeCondition($condition);
$db = $this->getOwner()::getDb();
$this->getOwner()::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;
}
/**
* Handles post-insert updates for the nested set structure when making a node root.
*
* If the current operation is {@see self::OPERATION_MAKE_ROOT} and the {@see treeAttribute} is enabled, this method
* sets the tree attribute of the node to its primary key and updates the corresponding record in the database.
*
* This ensures that the root node of a tree is correctly identified and its tree attribute is synchronized after
* insertion.
*
* @throws Exception if an unexpected error occurs during execution.
*
* Usage example:
* ```php
* // `afterInsert()` is called automatically to set the tree attribute
* $model->makeRoot();
* ```
*/
public function afterInsert(): void
{
if ($this->operation === self::OPERATION_MAKE_ROOT && $this->treeAttribute !== false) {
$this->getOwner()->setAttribute($this->treeAttribute, $this->getOwner()->getPrimaryKey());
$primaryKey = $this->getOwner()::primaryKey();
if (isset($primaryKey[0]) === false) {
throw new Exception('"' . get_class($this->getOwner()) . '" must have a primary key.');
}
$this->getOwner()::updateAll(
[
$this->treeAttribute => $this->getOwner()->getAttribute($this->treeAttribute),
],
[
$primaryKey[0] => $this->getOwner()->getAttribute($this->treeAttribute),
],
);
}
$this->operation = null;
$this->node = null;
}
/**
* Handles post-update operations for the nested set structure after a node modification.
*
* Executes the appropriate node movement logic based on the current operation type, ensuring the integrity and
* consistency of the nested set hierarchy after an update.
*
* This method is automatically triggered after an update event on the attached {@see ActiveRecord} model.
*
* The operation performed depends on the value of {@see operation}.
* - {@see self::OPERATION_APPEND_TO}: Moves the node as the last child of the target node.
* - {@see self::OPERATION_INSERT_AFTER}: Moves the node as the next sibling of the target node.
* - {@see self::OPERATION_INSERT_BEFORE}: Moves the node as the previous sibling of the target node.
* - {@see self::OPERATION_MAKE_ROOT}: Moves the node to become a root node.
* - {@see self::OPERATION_PREPEND_TO}: Moves the node as the first child of the target node.
*
* After the operation, the internal state is reset to prepare for subsequent operations.
*
* Usage example:
* ```php
* // `afterUpdate()` is called automatically to move the node
* $model->update();
* ```
*/
public function afterUpdate(): void
{
match (true) {
$this->operation === self::OPERATION_APPEND_TO && $this->node !== null =>
$this->moveNode($this->node, $this->node->getAttribute($this->rightAttribute), 1),
$this->operation === self::OPERATION_INSERT_AFTER && $this->node !== null =>
$this->moveNode($this->node, $this->node->getAttribute($this->rightAttribute) + 1, 0),
$this->operation === self::OPERATION_INSERT_BEFORE && $this->node !== null =>
$this->moveNode($this->node, $this->node->getAttribute($this->leftAttribute), 0),
$this->operation === self::OPERATION_MAKE_ROOT =>
$this->moveNodeAsRoot(),
$this->operation === self::OPERATION_PREPEND_TO && $this->node !== null =>
$this->moveNode($this->node, $this->node->getAttribute($this->leftAttribute) + 1, 1),
default => null,
};
$this->operation = null;
$this->node = null;
}
/**
* Appends the current node as the last child of the specified target node.
*
* - If the attached {@see ActiveRecord} is new, this method creates it as the last child of the given node.
* - If the record already exists, it moves the node as the last child of the target node, updating the nested set
* structure accordingly.
*
* This operation is essential for building and maintaining hierarchical data structures, such as categories or menu
* trees, where nodes can be dynamically inserted or reorganized within the tree.
*
* @param ActiveRecord $node Target node to which the current node will be appended as the last child.
* @param bool $runValidation Whether to perform validation before saving the record.
* @param array|null $attributes List of attributes that need to be saved. Defaults to `null`, meaning all
* attributes.
*
* @throws Exception if an unexpected error occurs during execution.
*
* @return bool Whether the operation was successful and the node was appended or moved.
*
* Usage example:
* ```php
* $category->appendTo($parentCategory);
* ```
*
* @phpstan-param array<string, mixed>|null $attributes
*/
public function appendTo(ActiveRecord $node, bool $runValidation = true, array|null $attributes = null): bool
{
$this->operation = self::OPERATION_APPEND_TO;
$this->node = $node;
return $this->getOwner()->save($runValidation, $attributes);
}
/**
* Handles pre-deletion validation and restrictions for the nested set node.
*
* Ensures that only valid nodes can be deleted and enforces restrictions on root node deletion unless the operation
* is explicitly set to delete with children.
*
* This method is automatically triggered before a node deletion event and is essential for maintaining the
* integrity of the nested set hierarchy.
*
* @throws Exception if an unexpected error occurs during execution.
* @throws NotSupportedException if the operation is not supported for the current node.
*
* Usage example:
* ```php
* // `beforeDelete()` is called automatically to validate the deletion
* $model->delete();
* ```
*/
public function beforeDelete(): void
{
if ($this->getOwner()->getIsNewRecord()) {
throw new Exception('Can not delete a node when it is new record.');
}
if ($this->operation !== self::OPERATION_DELETE_WITH_CHILDREN && $this->getOwner()->isRoot()) {
throw new NotSupportedException(
'Method "' . get_class($this->getOwner()) . '::delete" is not supported for deleting root nodes.',
);
}
$this->getOwner()->refresh();
}
/**
* Handles pre-insert operations for the nested set structure before a node is inserted.
*
* Determines the appropriate insertion logic based on the current operation type and the state of the target node.
*
* This method is automatically triggered before an insert event on the attached {@see ActiveRecord} model.
*
* It ensures that the nested set attributes are correctly prepared for the intended operation, such as making a
* node root, prepending/appending as a child, or inserting as a sibling.
*
* The operation performed depends on the value of {@see $operation}.
* - {@see self::OPERATION_APPEND_TO}: Prepares the node to be inserted as the last child of the target node.
* - {@see self::OPERATION_INSERT_AFTER}: Prepares the node to be inserted as the next sibling of the target node.
* - {@see self::OPERATION_INSERT_BEFORE}: Prepares the node to be inserted as the previous sibling of the target
* node.
* - {@see self::OPERATION_MAKE_ROOT}: Prepares the node to be inserted as a root node.
* - {@see self::OPERATION_PREPEND_TO}: Prepares the node to be inserted as the first child of the target node.
*
* If the target node is not new, it is refreshed to ensure up-to-date attribute values before insertion.
*
* @throws Exception if an unexpected error occurs during execution.
* @throws NotSupportedException if the operation is not supported for the current node.
*
* Usage example:
* ```php
* // `beforeInsert()` is called automatically to prepare the node for insertion
* $model->insert();
* ```
*/
public function beforeInsert(): void
{
if ($this->node?->getIsNewRecord() === false) {
$this->node->refresh();
}
$nodeLeftValue = $this->node?->getAttribute($this->leftAttribute) ?? 0;
$nodeRightValue = $this->node?->getAttribute($this->rightAttribute) ?? 0;
match ($this->operation) {
self::OPERATION_APPEND_TO => $this->beforeInsertNode($nodeRightValue, 1),
self::OPERATION_INSERT_AFTER => $this->beforeInsertNode($nodeRightValue + 1, 0),
self::OPERATION_INSERT_BEFORE => $this->beforeInsertNode($nodeLeftValue, 0),
self::OPERATION_MAKE_ROOT => $this->beforeInsertRootNode(),
self::OPERATION_PREPEND_TO => $this->beforeInsertNode($nodeLeftValue + 1, 1),
default => throw new NotSupportedException(
'Method "' . get_class($this->getOwner()) . '::insert" is not supported for inserting new nodes.',
),
};
}
/**
* Handles pre-update validation and restrictions for the nested set node.
*
* Ensures that only valid node movements are allowed and enforces restrictions on moving nodes within the tree
* structure.
*
* This method is automatically triggered before an update event on the attached {@see ActiveRecord} model and is
* essential for maintaining the integrity of the nested set hierarchy during node movement operations.
*
* The operation performed depends on the value of {@see $operation}.
* - {@see self::OPERATION_MAKE_ROOT}: Validates that the node can be moved as root and that the tree attribute is
* enabled.
* - {@see self::OPERATION_INSERT_AFTER}, {@see self::OPERATION_INSERT_BEFORE}: Prevents moving a node when the
* target node is root.
* - {@see self::OPERATION_APPEND_TO}, {@see self::OPERATION_PREPEND_TO}: Prevents moving a node to an invalid
* target (new record, same node, or child node).
*
* @throws Exception if an unexpected error occurs during execution.
*
* Usage example:
* ```php
* // `beforeUpdate()` is called automatically to validate the movement
* $model->update();
* ```
*/
public function beforeUpdate(): void
{
if ($this->node?->getIsNewRecord() === false) {
$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->getOwner()->isRoot()) {
throw new Exception('Can not move the root node as the root.');
}
break;
case self::OPERATION_INSERT_AFTER:
case self::OPERATION_INSERT_BEFORE:
if ($this->node?->isRoot() === true) {
throw new Exception('Can not move a node when the target node is root.');
}
// no break
case self::OPERATION_APPEND_TO:
case self::OPERATION_PREPEND_TO:
if ($this->node?->getIsNewRecord() === true) {
throw new Exception('Can not move a node when the target node is new record.');
}
if ($this->node !== null && $this->getOwner()->equals($this->node)) {
throw new Exception('Can not move a node when the target node is same.');
}
if ($this->node !== null && $this->node->isChildOf($this->getOwner())) {
throw new Exception('Can not move a node when the target node is child.');
}
}
}
/**
* Returns an {@see ActiveQuery} for the children of the current node, optionally limited by depth.
*
* Retrieves all descendant nodes that are children of the current node, ordered by the left attribute ascending.
*
* If the optional `$depth` parameter is provided, only children up to the specified depth relative to the current
* node are included.
*
* The query automatically applies the tree attribute condition if configured, ensuring correct results for
* multi-tree structures.
*
* @param int|null $depth Maximum depth relative to the current node, or `null` for all descendants.
*
* @return ActiveQuery ActiveQuery instance for fetching child nodes.
*
* Usage example:
* ```php
* // Retrieves all children of the current node
* $children = $model->children();
* ```
*
* @phpstan-return ActiveQuery<T>
*/
public function children(int|null $depth = null): ActiveQuery
{
$condition = [
'and',
[
'>',
$this->leftAttribute, $this->getOwner()->getAttribute($this->leftAttribute),
],
[
'<',
$this->rightAttribute, $this->getOwner()->getAttribute($this->rightAttribute),
],
];
if ($depth !== null) {
$condition[] = [
'<=',
$this->depthAttribute,
$this->getOwner()->getAttribute($this->depthAttribute) + $depth,
];
}
$this->applyTreeAttributeCondition($condition);
return $this->getOwner()::find()->andWhere($condition)->addOrderBy([$this->leftAttribute => SORT_ASC]);
}
/**
* Deletes the current node and all its descendant nodes from the nested set tree.
*
* Removes the node to which this behavior is attached, along with all its children, from the hierarchical
* structure.
*
* This method sets the internal operation state to {@see self::OPERATION_DELETE_WITH_CHILDREN} and performs the
* deletion within a database transaction if the model is not already transactional for delete operations.
*
* The deletion is delegated to {@see deleteWithChildrenInternal()}, which executes the actual removal logic.
*
* If the deletion fails, the transaction is rolled back to maintain data integrity.
*
* @throws Exception if an unexpected error occurs during execution.
*
* @return bool|int Number of rows deleted, or false if the deletion is unsuccessful.
*
* Usage example:
* ```php
* $model->deleteWithChildren();
* ```
*/
public function deleteWithChildren(): bool|int
{
$this->operation = self::OPERATION_DELETE_WITH_CHILDREN;
if ($this->getOwner()->isTransactional(ActiveRecord::OP_DELETE) !== false) {
return $this->deleteWithChildrenInternal();
}
$transaction = $this->getOwner()::getDb()->beginTransaction();
try {
match ($result = $this->deleteWithChildrenInternal()) {
false => $transaction->rollBack(),
default => $transaction->commit(),
};
return $result;
} catch (Exception $e) {
$transaction->rollBack();
throw $e;
}
}
/**
* Declares event handlers for {@see ActiveRecord} lifecycle events.
*
* This method enables the behavior to automatically respond to insert, update, and delete operations on the
* attached {@see ActiveRecord} model by invoking the appropriate handler methods.
*
* It ensures that the nested set structure remains consistent during model persistence operations.
*
* @return array Event-to-handler map for {@see ActiveRecord} lifecycle events.
*
* Usage example:
* ```php
* // Behavior will automatically handle events like `beforeInsert`, `afterInsert`, etc.
* $model->attachBehavior('nestedSets', new NestedSetsBehavior());
* ```
*
* @phpstan-return string[]
*/
public function events(): array
{
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',
];
}
/**
* Inserts the current node as the next sibling of the specified target node or moves it if it already exists.
*
* - If the attached {@see ActiveRecord} is a new record, this method creates it as the next sibling of the given
* node.
* - If the record already exists, it moves the node as the next sibling of the target node, updating the nested set
* structure accordingly.
*
* This operation is essential for maintaining hierarchical data structures where nodes can be dynamically inserted
* or reorganized within the tree at the same level as the target node.
*
* The method sets the internal operation state to {@see self::OPERATION_INSERT_AFTER} and stores the reference to
* the target node.
*
* The actual insertion or movement is performed by saving the owner model, which triggers the appropriate lifecycle
* events and updates the tree structure.
*
* @param ActiveRecord $node Target node after which the current node will be inserted as the next sibling.
* @param bool $runValidation Whether to perform validation before saving the record.
* @param array|null $attributes List of attributes that need to be saved. Defaults to `null`, meaning all
* attributes.
*
* @throws Exception if an unexpected error occurs during execution.
*
* @return bool Whether the operation was successful and the node was inserted or moved.
*
* Usage example:
* ```php
* $category->insertAfter($siblingCategory);
* ```
*
* @phpstan-param array<string, mixed>|null $attributes
*/
public function insertAfter(ActiveRecord $node, bool $runValidation = true, array|null $attributes = null): bool
{
$this->operation = self::OPERATION_INSERT_AFTER;
$this->node = $node;
return $this->getOwner()->save($runValidation, $attributes);
}
/**
* Inserts the current node as the previous sibling of the specified target node or moves it if it already exists.
*
* - If the attached {@see ActiveRecord} is a new record, this method creates it as the previous sibling of the
* given node.
* - If the record already exists, it moves the node as the previous sibling of the target node, updating the nested
* set structure accordingly.
*
* This operation is essential for maintaining hierarchical data structures where nodes can be dynamically inserted
* or reorganized within the tree at the same level as the target node.
*
* The method sets the internal operation state to {@see self::OPERATION_INSERT_BEFORE} and stores the reference to
* the target node.
*
* The actual insertion or movement is performed by saving the owner model, which triggers the appropriate lifecycle
* events and updates the tree structure.
*
* @param ActiveRecord $node Target node before which the current node will be inserted as the previous sibling.
* @param bool $runValidation Whether to perform validation before saving the record.
* @param array|null $attributes List of attributes that need to be saved. Defaults to `null`, meaning all
* attributes.
*
* @throws Exception if an unexpected error occurs during execution.
*
* @return bool Whether the operation was successful and the node was inserted or moved.
*
* Usage example:
* ```php
* $category->insertBefore($siblingCategory);
* ```
*
* @phpstan-param array<string, mixed>|null $attributes
*/
public function insertBefore(ActiveRecord $node, bool $runValidation = true, array|null $attributes = null): bool
{
$this->operation = self::OPERATION_INSERT_BEFORE;
$this->node = $node;
return $this->getOwner()->save($runValidation, $attributes);
}
/**
* Determines whether the current node is a direct or indirect child of the specified parent node.
*
* Evaluates the nested set boundaries to check if the node to which this behavior is attached is contained within
* the left and right boundaries of the given parent node.
*
* If the behavior is configured for multi-tree support (that is, {@see treeAttribute} is enabled), the method also
* verifies that both nodes belong to the same tree by comparing their tree attribute values.
*
* This method is useful for validating hierarchical relationships, enforcing tree integrity, and implementing
* access or movement restrictions based on parent-child relationships within the nested set structure.
*
* @param ActiveRecord $node Parent node to check against.
*
* @return bool Whether the current node is a child (descendant) of the specified parent node.
*
* Usage example:
* ```php
* if ($category->isChildOf($parentCategory)) {
* // Perform logic for child nodes
* }
* ```
*/
public function isChildOf(ActiveRecord $node): bool
{
$owner = $this->getOwner();
$currentLeft = $owner->getAttribute($this->leftAttribute);
$currentRight = $owner->getAttribute($this->rightAttribute);
$nodeLeft = $node->getAttribute($this->leftAttribute);
$nodeRight = $node->getAttribute($this->rightAttribute);
if ($currentLeft <= $nodeLeft || $currentRight >= $nodeRight) {
return false;
}
if ($this->treeAttribute !== false) {
return $owner->getAttribute($this->treeAttribute) === $node->getAttribute($this->treeAttribute);
}
return true;
}
/**
* Determines whether the current node is a leaf node in the nested set tree.
*
* Evaluates the left and right attribute values of the node to check if it has no children, according to the nested
* sets model.
*
* A node is considered a leaf if the difference between its right and left attribute values is exactly one,
* indicating that it has no child nodes within the tree structure.
*
* This method is useful for identifying terminal nodes in hierarchical data, enabling logic for deletion, movement,
* or display of leaf nodes in tree-based structures.
*
* @return bool Whether the current node is a leaf node (has no children).
*
* Usage example:
* ```php
* if ($category->isLeaf()) {
* // Perform logic for leaf nodes
* }
* ```
*/
public function isLeaf(): bool
{
return $this->getOwner()
->getAttribute($this->rightAttribute) - $this->getOwner()->getAttribute($this->leftAttribute) === 1;
}
/**
* Determines whether the current node is a root node in the nested set tree.
*
* Evaluates the left attribute value of the node to check if it is positioned as the root node within the tree
* structure.
*
* A node is considered root if its left attribute value is exactly one, which is the standard convention in the
* nested sets model for identifying the root node of a tree.
*
* This method is useful for validating root status, enforcing tree integrity, and implementing logic that applies
* only to root nodes in hierarchical data structures.
*
* @return bool Whether the current node is a root node (left attribute equals one).
*
* Usage example:
* ```php
* if ($category->isRoot()) {
* // Perform logic for root nodes
* }
* ```
*/
public function isRoot(): bool
{
return $this->getOwner()->getAttribute($this->leftAttribute) === 1;
}
/**
* Retrieves all leaf nodes that are descendants of the current node.
*
* Returns an {@see ActiveQuery} representing all leaf nodes (nodes without children) that are contained within the
* left and right boundaries of the node to which this behavior is attached.
*
* A node is considered a leaf if its right attribute value is exactly one greater than its left attribute value.
*
* This method constructs a query to select all such nodes that are descendants of the current node, ordered by the
* left attribute in ascending order.
*
* This is useful for efficiently retrieving all terminal nodes in a subtree, such as for rendering category trees,
* generating navigation menus, or performing operations on leaf nodes only.
*
* @return ActiveQuery ActiveQuery instance for all leaf nodes under the current node.
*
* Usage example:
* ```php
* // Get all leaf nodes under the current node
* $leaves = $model->leaves()->all();
* ```
*
* @phpstan-return ActiveQuery<T>
*/
public function leaves(): ActiveQuery
{
$condition = [
'and',
[
'>',
$this->leftAttribute, $this->getOwner()->getAttribute($this->leftAttribute),
],
[
'<',
$this->rightAttribute, $this->getOwner()->getAttribute($this->rightAttribute),
],
[
$this->rightAttribute => new Expression(
$this->getOwner()::getDb()->quoteColumnName($this->leftAttribute) . '+ 1',
),
],
];
$this->applyTreeAttributeCondition($condition);
return $this->getOwner()::find()->andWhere($condition)->addOrderBy([$this->leftAttribute => SORT_ASC]);
}
/**
* Creates the root node if the active record is new, or moves it as the root node in the nested set tree.
*
* Sets the internal operation state to {@see self::OPERATION_MAKE_ROOT} and triggers the save process on the owner
* model.
*
* - If the attached {@see ActiveRecord} is a new record, this method creates it as the root node of a new tree.
* - If the record already exists, it moves the node to become the root node, updating the nested set structure
* accordingly.
*
* This operation is essential for initializing or reorganizing hierarchical data structures, such as category
* trees, where nodes can be promoted to root status or new trees can be started.
*
* The actual creation or movement is performed by saving the owner model, which triggers the appropriate lifecycle
* events and updates the tree structure.
*
* @param bool $runValidation Whether to perform validation before saving the record.
* @param array|null $attributes List of attributes that need to be saved. Defaults to `null`, meaning all
* attributes.
*
* @throws Exception if an unexpected error occurs during execution.
*
* @return bool Whether the operation was successful and the node was created or moved as root.
*
* Usage example:
* ```php
* $category->makeRoot();
* ```
*
* @phpstan-param array<string, mixed>|null $attributes
*/
public function makeRoot(bool $runValidation = true, array|null $attributes = null): bool
{
$this->operation = self::OPERATION_MAKE_ROOT;
return $this->getOwner()->save($runValidation, $attributes);
}
/**
* Returns an {@see ActiveQuery} for the next sibling node in the nested set tree.
*
* Constructs a query to retrieve the node whose left attribute value is exactly one greater than the right
* attribute value of the current node, selecting the immediate next sibling at the same hierarchical level.
*
* If the behavior is configured for multi-tree support (that is, {@see treeAttribute} is enabled), the query will
* include a condition to ensure that the sibling belongs to the same tree as the current node.
*
* This method is useful for traversing sibling nodes in hierarchical data structures, such as categories or menu
* trees, and enables efficient navigation or manipulation of adjacent nodes within the same parent.
*
* @return ActiveQuery ActiveQuery instance for the next sibling node, or an empty result if there is no next
* sibling.
*
* Usage example:
* ```php
* // Get the next sibling of the current node
* $nextSibling = $model->next()->one();
* ```
*
* @phpstan-return ActiveQuery<T>
*/
public function next(): ActiveQuery
{
$condition = [$this->leftAttribute => $this->getOwner()->getAttribute($this->rightAttribute) + 1];
$this->applyTreeAttributeCondition($condition);
return $this->getOwner()::find()->andWhere($condition);
}
/**
* Retrieves all ancestor nodes (parents) of the current node in the nested set tree.
*
* Returns an {@see ActiveQuery} representing all parent nodes of the node to which this behavior is attached,
* ordered by the left attribute in ascending order.
*
* The query includes all nodes that enclose the current node according to the nested sets model, optionally limited
* by a specified depth.
*
* This method is useful for traversing the hierarchy upwards, such as for building breadcrumb navigation,
* validating ancestry, or applying logic based on parent relationships in hierarchical data structures.
*
* If the optional `$depth` parameter is provided, only parents within the specified depth from the current node
* will be included in the result.
*
* @param int|null $depth Optional depth limit for parent retrieval.
* - If set, only parents within this depth from the current node are returned.
* - If `null`, all ancestor nodes are returned.
*
* @return ActiveQuery ActiveQuery instance for all parent nodes of the current node, ordered by left attribute.
*
* Usage example:
* ```php
* // Get all parent nodes (ancestors) of the current node
* $parents = $model->parents()->all();
*
* // Get parents up to 2 levels above the current node
* $limitedParents = $model->parents(2)->all();
* ```
*
* @phpstan-return ActiveQuery<T>
*/
public function parents(int|null $depth = null): ActiveQuery
{
$condition = [
'and',
[
'<',
$this->leftAttribute, $this->getOwner()->getAttribute($this->leftAttribute),
],
[
'>',
$this->rightAttribute, $this->getOwner()->getAttribute($this->rightAttribute),
],
];
if ($depth !== null) {
$condition[] = [
'>=',
$this->depthAttribute, $this->getOwner()->getAttribute($this->depthAttribute) - $depth,
];
}
$this->applyTreeAttributeCondition($condition);
return $this->getOwner()::find()->andWhere($condition)->addOrderBy([$this->leftAttribute => SORT_ASC]);
}
/**
* Inserts the current node as the first child of the specified target node or moves it if it already exists.
*
* - If the attached {@see ActiveRecord} is a new record, this method creates it as the first child of the given
* node.
* - If the record already exists, it moves the node as the first child of the target node, updating the nested set
* structure accordingly.
*
* This operation is essential for building and maintaining hierarchical data structures, such as categories or menu
* trees, where nodes can be dynamically inserted or reorganized within the tree.
*
* The method sets the internal operation state to {@see self::OPERATION_PREPEND_TO} and stores the reference to the
* target node.
*
* The actual insertion or movement is performed by saving the owner model, which triggers the appropriate lifecycle
* events and updates the tree structure.
*
* @param ActiveRecord $node Target node to which the current node will be prepended as the first child.
* @param bool $runValidation Whether to perform validation before saving the record.
* @param array|null $attributes List of attributes that need to be saved. Defaults to `null`, meaning all
* attributes.
*
* @throws Exception if an unexpected error occurs during execution.
*
* @return bool Whether the operation was successful and the node was prepended or moved.
*
* Usage example:
* ```php
* $category->prependTo($parentCategory);
* ```
*
* @phpstan-param array<string, mixed>|null $attributes
*/
public function prependTo(ActiveRecord $node, bool $runValidation = true, array|null $attributes = null): bool
{
$this->operation = self::OPERATION_PREPEND_TO;
$this->node = $node;
return $this->getOwner()->save($runValidation, $attributes);
}
/**
* Returns an {@see ActiveQuery} for the previous sibling node in the nested set tree.
*
* Constructs a query to retrieve the node whose right attribute value is exactly one less than the left attribute
* value of the current node, selecting the immediate previous sibling at the same hierarchical level.
*
* If the behavior is configured for multi-tree support (that is, {@see treeAttribute} is enabled), the query will
* include a condition to ensure that the sibling belongs to the same tree as the current node.
*
* This method is useful for traversing sibling nodes in hierarchical data structures, such as categories or menu
* trees, and enables efficient navigation or manipulation of adjacent nodes within the same parent.
*
* @return ActiveQuery ActiveQuery instance for the previous sibling node, or an empty result if there is no
* previous sibling.
*
* Usage example:
* ```php
* // Get the previous sibling of the current node
* $prevSibling = $model->prev()->one();
* ```
*
* @phpstan-return ActiveQuery<T>
*/
public function prev(): ActiveQuery
{
$condition = [$this->rightAttribute => $this->getOwner()->getAttribute($this->leftAttribute) - 1];
$this->applyTreeAttributeCondition($condition);
return $this->getOwner()::find()->andWhere($condition);
}
/**