-
Notifications
You must be signed in to change notification settings - Fork 478
/
Copy pathQueryBuilder.php
1092 lines (922 loc) · 27.9 KB
/
QueryBuilder.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
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
namespace Kalnoy\Nestedset;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\Query\Builder as Query;
use Illuminate\Database\Query\Builder as BaseQueryBuilder;
use Illuminate\Support\Arr;
use LogicException;
use Illuminate\Database\Query\Expression;
class QueryBuilder extends Builder
{
/**
* @var NodeTrait|Model
*/
protected $model;
/**
* Get node's `lft` and `rgt` values.
*
* @since 2.0
*
* @param mixed $id
* @param bool $required
*
* @return array
*/
public function getNodeData($id, $required = false)
{
$lftName = $this->model->getLftName();
$rgtName = $this->model->getRgtName();
$data = $this->toBase()
->where($this->model->getKeyName(), '=', $id)
->first([$lftName, $rgtName]);
if ( ! $data && $required) {
throw new ModelNotFoundException;
}
// Ensure that the result only contains the required attributes in
// correct order and nothing else.
// The query above might accidentally return more attributes, if
// a global scope is defined for the query by the base model.
return $data ? [$lftName => $data[$lftName], $rgtName => $data[$rgtName]] : [];
}
/**
* Get plain node data.
*
* @since 2.0
*
* @param mixed $id
* @param bool $required
*
* @return array
*/
public function getPlainNodeData($id, $required = false)
{
return array_values($this->getNodeData($id, $required));
}
/**
* Scope limits query to select just root node.
*
* @return $this
*/
public function whereIsRoot()
{
$this->query->whereNull($this->model->getParentIdName());
return $this;
}
/**
* Limit results to ancestors of specified node.
*
* @since 2.0
*
* @param mixed $id
* @param bool $andSelf
*
* @param string $boolean
*
* @return $this
*/
public function whereAncestorOf($id, $andSelf = false, $boolean = 'and')
{
$keyName = $this->model->getTable() . '.' . $this->model->getKeyName();
if (NestedSet::isNode($id)) {
$value = '?';
$this->query->addBinding($id->getRgt());
$id = $id->getKey();
} else {
$valueQuery = $this->model
->newQuery()
->toBase()
->select("_.".$this->model->getRgtName())
->from($this->model->getTable().' as _')
->where($this->model->getKeyName(), '=', $id)
->limit(1);
$this->query->mergeBindings($valueQuery);
$value = '('.$valueQuery->toSql().')';
}
$this->query->whereNested(function ($inner) use ($value, $andSelf, $id, $keyName) {
list($lft, $rgt) = $this->wrappedColumns();
$wrappedTable = $this->query->getGrammar()->wrapTable($this->model->getTable());
$inner->whereRaw("{$value} between {$wrappedTable}.{$lft} and {$wrappedTable}.{$rgt}");
if ( ! $andSelf) {
$inner->where($keyName, '<>', $id);
}
}, $boolean);
return $this;
}
/**
* @param $id
* @param bool $andSelf
*
* @return $this
*/
public function orWhereAncestorOf($id, $andSelf = false)
{
return $this->whereAncestorOf($id, $andSelf, 'or');
}
/**
* @param $id
*
* @return QueryBuilder
*/
public function whereAncestorOrSelf($id)
{
return $this->whereAncestorOf($id, true);
}
/**
* Get ancestors of specified node.
*
* @since 2.0
*
* @param mixed $id
* @param array $columns
*
* @return \Kalnoy\Nestedset\Collection
*/
public function ancestorsOf($id, array $columns = array( '*' ))
{
return $this->whereAncestorOf($id)->get($columns);
}
/**
* @param $id
* @param array $columns
*
* @return \Kalnoy\Nestedset\Collection
*/
public function ancestorsAndSelf($id, array $columns = [ '*' ])
{
return $this->whereAncestorOf($id, true)->get($columns);
}
/**
* Add node selection statement between specified range.
*
* @since 2.0
*
* @param array $values
* @param string $boolean
* @param bool $not
*
* @return $this
*/
public function whereNodeBetween($values, $boolean = 'and', $not = false)
{
$this->query->whereBetween($this->model->getTable() . '.' . $this->model->getLftName(), $values, $boolean, $not);
return $this;
}
/**
* Add node selection statement between specified range joined with `or` operator.
*
* @since 2.0
*
* @param array $values
*
* @return $this
*/
public function orWhereNodeBetween($values)
{
return $this->whereNodeBetween($values, 'or');
}
/**
* Add constraint statement to descendants of specified node.
*
* @since 2.0
*
* @param mixed $id
* @param string $boolean
* @param bool $not
* @param bool $andSelf
*
* @return $this
*/
public function whereDescendantOf($id, $boolean = 'and', $not = false,
$andSelf = false
) {
if (NestedSet::isNode($id)) {
$data = $id->getBounds();
} else {
$data = $this->model->newNestedSetQuery()
->getPlainNodeData($id, true);
}
// Don't include the node
if ( ! $andSelf) {
++$data[0];
}
return $this->whereNodeBetween($data, $boolean, $not);
}
/**
* @param mixed $id
*
* @return QueryBuilder
*/
public function whereNotDescendantOf($id)
{
return $this->whereDescendantOf($id, 'and', true);
}
/**
* @param mixed $id
*
* @return QueryBuilder
*/
public function orWhereDescendantOf($id)
{
return $this->whereDescendantOf($id, 'or');
}
/**
* @param mixed $id
*
* @return QueryBuilder
*/
public function orWhereNotDescendantOf($id)
{
return $this->whereDescendantOf($id, 'or', true);
}
/**
* @param $id
* @param string $boolean
* @param bool $not
*
* @return $this
*/
public function whereDescendantOrSelf($id, $boolean = 'and', $not = false)
{
return $this->whereDescendantOf($id, $boolean, $not, true);
}
/**
* Get descendants of specified node.
*
* @since 2.0
*
* @param mixed $id
* @param array $columns
* @param bool $andSelf
*
* @return Collection
*/
public function descendantsOf($id, array $columns = [ '*' ], $andSelf = false)
{
try {
return $this->whereDescendantOf($id, 'and', false, $andSelf)->get($columns);
}
catch (ModelNotFoundException $e) {
return $this->model->newCollection();
}
}
/**
* @param $id
* @param array $columns
*
* @return Collection
*/
public function descendantsAndSelf($id, array $columns = [ '*' ])
{
return $this->descendantsOf($id, $columns, true);
}
/**
* @param $id
* @param $operator
* @param $boolean
*
* @return $this
*/
protected function whereIsBeforeOrAfter($id, $operator, $boolean)
{
if (NestedSet::isNode($id)) {
$value = '?';
$this->query->addBinding($id->getLft());
} else {
$valueQuery = $this->model
->newQuery()
->toBase()
->select('_n.'.$this->model->getLftName())
->from($this->model->getTable().' as _n')
->where('_n.'.$this->model->getKeyName(), '=', $id);
$this->query->mergeBindings($valueQuery);
$value = '('.$valueQuery->toSql().')';
}
list($lft,) = $this->wrappedColumns();
$this->query->whereRaw("{$lft} {$operator} {$value}", [ ], $boolean);
return $this;
}
/**
* Constraint nodes to those that are after specified node.
*
* @since 2.0
*
* @param mixed $id
* @param string $boolean
*
* @return $this
*/
public function whereIsAfter($id, $boolean = 'and')
{
return $this->whereIsBeforeOrAfter($id, '>', $boolean);
}
/**
* Constraint nodes to those that are before specified node.
*
* @since 2.0
*
* @param mixed $id
* @param string $boolean
*
* @return $this
*/
public function whereIsBefore($id, $boolean = 'and')
{
return $this->whereIsBeforeOrAfter($id, '<', $boolean);
}
/**
* @return $this
*/
public function whereIsLeaf()
{
list($lft, $rgt) = $this->wrappedColumns();
return $this->whereRaw("$lft = $rgt - 1");
}
/**
* @param array $columns
*
* @return Collection
*/
public function leaves(array $columns = [ '*'])
{
return $this->whereIsLeaf()->get($columns);
}
/**
* Include depth level into the result.
*
* @param string $as
*
* @return $this
*/
public function withDepth($as = 'depth')
{
if ($this->query->columns === null) $this->query->columns = [ '*' ];
$table = $this->wrappedTable();
list($lft, $rgt) = $this->wrappedColumns();
$alias = '_d';
$wrappedAlias = $this->query->getGrammar()->wrapTable($alias);
$query = $this->model
->newScopedQuery('_d')
->toBase()
->selectRaw('count(1) - 1')
->from($this->model->getTable().' as '.$alias)
->whereRaw("{$table}.{$lft} between {$wrappedAlias}.{$lft} and {$wrappedAlias}.{$rgt}");
$this->query->selectSub($query, $as);
return $this;
}
/**
* Get wrapped `lft` and `rgt` column names.
*
* @since 2.0
*
* @return array
*/
protected function wrappedColumns()
{
$grammar = $this->query->getGrammar();
return [
$grammar->wrap($this->model->getLftName()),
$grammar->wrap($this->model->getRgtName()),
];
}
/**
* Get a wrapped table name.
*
* @since 2.0
*
* @return string
*/
protected function wrappedTable()
{
return $this->query->getGrammar()->wrapTable($this->getQuery()->from);
}
/**
* Wrap model's key name.
*
* @since 2.0
*
* @return string
*/
protected function wrappedKey()
{
return $this->query->getGrammar()->wrap($this->model->getKeyName());
}
/**
* Exclude root node from the result.
*
* @return $this
*/
public function withoutRoot()
{
$this->query->whereNotNull($this->model->getParentIdName());
return $this;
}
/**
* Equivalent of `withoutRoot`.
*
* @since 2.0
* @deprecated since v4.1
*
* @return $this
*/
public function hasParent()
{
$this->query->whereNotNull($this->model->getParentIdName());
return $this;
}
/**
* Get only nodes that have children.
*
* @since 2.0
* @deprecated since v4.1
*
* @return $this
*/
public function hasChildren()
{
list($lft, $rgt) = $this->wrappedColumns();
$this->query->whereRaw("{$rgt} > {$lft} + 1");
return $this;
}
/**
* Order by node position.
*
* @param string $dir
*
* @return $this
*/
public function defaultOrder($dir = 'asc')
{
$this->query->orders = null;
$this->query->orderBy($this->model->getLftName(), $dir);
return $this;
}
/**
* Order by reversed node position.
*
* @return $this
*/
public function reversed()
{
return $this->defaultOrder('desc');
}
/**
* Move a node to the new position.
*
* @param mixed $key
* @param int $position
*
* @return int
*/
public function moveNode($key, $position)
{
list($lft, $rgt) = $this->model->newNestedSetQuery()
->getPlainNodeData($key, true);
if ($lft < $position && $position <= $rgt) {
throw new LogicException('Cannot move node into itself.');
}
// Get boundaries of nodes that should be moved to new position
$from = min($lft, $position);
$to = max($rgt, $position - 1);
// The height of node that is being moved
$height = $rgt - $lft + 1;
// The distance that our node will travel to reach it's destination
$distance = $to - $from + 1 - $height;
// If no distance to travel, just return
if ($distance === 0) {
return 0;
}
if ($position > $lft) {
$height *= -1;
} else {
$distance *= -1;
}
$params = compact('lft', 'rgt', 'from', 'to', 'height', 'distance');
$boundary = [ $from, $to ];
$query = $this->toBase()->where(function (Query $inner) use ($boundary) {
$inner->whereBetween($this->model->getLftName(), $boundary);
$inner->orWhereBetween($this->model->getRgtName(), $boundary);
});
return $query->update($this->patch($params));
}
/**
* Make or remove gap in the tree. Negative height will remove gap.
*
* @since 2.0
*
* @param int $cut
* @param int $height
*
* @return int
*/
public function makeGap($cut, $height)
{
$params = compact('cut', 'height');
$query = $this->toBase()->whereNested(function (Query $inner) use ($cut) {
$inner->where($this->model->getLftName(), '>=', $cut);
$inner->orWhere($this->model->getRgtName(), '>=', $cut);
});
return $query->update($this->patch($params));
}
/**
* Get patch for columns.
*
* @since 2.0
*
* @param array $params
*
* @return array
*/
protected function patch(array $params)
{
$grammar = $this->query->getGrammar();
$columns = [];
foreach ([ $this->model->getLftName(), $this->model->getRgtName() ] as $col) {
$columns[$col] = $this->columnPatch($grammar->wrap($col), $params);
}
return $columns;
}
/**
* Get patch for single column.
*
* @since 2.0
*
* @param string $col
* @param array $params
*
* @return string
*/
protected function columnPatch($col, array $params)
{
extract($params);
/** @var int $height */
if ($height > 0) $height = '+'.$height;
if (isset($cut)) {
return new Expression("case when {$col} >= {$cut} then {$col}{$height} else {$col} end");
}
/** @var int $distance */
/** @var int $lft */
/** @var int $rgt */
/** @var int $from */
/** @var int $to */
if ($distance > 0) $distance = '+'.$distance;
return new Expression("case ".
"when {$col} between {$lft} and {$rgt} then {$col}{$distance} ". // Move the node
"when {$col} between {$from} and {$to} then {$col}{$height} ". // Move other nodes
"else {$col} end"
);
}
/**
* Get statistics of errors of the tree.
*
* @since 2.0
*
* @return array
*/
public function countErrors()
{
$checks = [];
// Check if lft and rgt values are ok
$checks['oddness'] = $this->getOdnessQuery();
// Check if lft and rgt values are unique
$checks['duplicates'] = $this->getDuplicatesQuery();
// Check if parent_id is set correctly
$checks['wrong_parent'] = $this->getWrongParentQuery();
// Check for nodes that have missing parent
$checks['missing_parent' ] = $this->getMissingParentQuery();
$query = $this->query->newQuery();
foreach ($checks as $key => $inner) {
$inner->selectRaw('count(1)');
$query->selectSub($inner, $key);
}
return (array)$query->first();
}
/**
* @return BaseQueryBuilder
*/
protected function getOdnessQuery()
{
return $this->model
->newNestedSetQuery()
->toBase()
->whereNested(function (BaseQueryBuilder $inner) {
list($lft, $rgt) = $this->wrappedColumns();
$inner->whereRaw("{$lft} >= {$rgt}")
->orWhereRaw("({$rgt} - {$lft}) % 2 = 0");
});
}
/**
* @return BaseQueryBuilder
*/
protected function getDuplicatesQuery()
{
$table = $this->wrappedTable();
$keyName = $this->wrappedKey();
$firstAlias = 'c1';
$secondAlias = 'c2';
$waFirst = $this->query->getGrammar()->wrapTable($firstAlias);
$waSecond = $this->query->getGrammar()->wrapTable($secondAlias);
$query = $this->model
->newNestedSetQuery($firstAlias)
->toBase()
->from($this->query->raw("{$table} as {$waFirst}, {$table} {$waSecond}"))
->whereRaw("{$waFirst}.{$keyName} < {$waSecond}.{$keyName}")
->whereNested(function (BaseQueryBuilder $inner) use ($waFirst, $waSecond) {
list($lft, $rgt) = $this->wrappedColumns();
$inner->orWhereRaw("{$waFirst}.{$lft}={$waSecond}.{$lft}")
->orWhereRaw("{$waFirst}.{$rgt}={$waSecond}.{$rgt}")
->orWhereRaw("{$waFirst}.{$lft}={$waSecond}.{$rgt}")
->orWhereRaw("{$waFirst}.{$rgt}={$waSecond}.{$lft}");
});
return $this->model->applyNestedSetScope($query, $secondAlias);
}
/**
* @return BaseQueryBuilder
*/
protected function getWrongParentQuery()
{
$table = $this->wrappedTable();
$keyName = $this->wrappedKey();
$grammar = $this->query->getGrammar();
$parentIdName = $grammar->wrap($this->model->getParentIdName());
$parentAlias = 'p';
$childAlias = 'c';
$intermAlias = 'i';
$waParent = $grammar->wrapTable($parentAlias);
$waChild = $grammar->wrapTable($childAlias);
$waInterm = $grammar->wrapTable($intermAlias);
$query = $this->model
->newNestedSetQuery('c')
->toBase()
->from($this->query->raw("{$table} as {$waChild}, {$table} as {$waParent}, $table as {$waInterm}"))
->whereRaw("{$waChild}.{$parentIdName}={$waParent}.{$keyName}")
->whereRaw("{$waInterm}.{$keyName} <> {$waParent}.{$keyName}")
->whereRaw("{$waInterm}.{$keyName} <> {$waChild}.{$keyName}")
->whereNested(function (BaseQueryBuilder $inner) use ($waInterm, $waChild, $waParent) {
list($lft, $rgt) = $this->wrappedColumns();
$inner->whereRaw("{$waChild}.{$lft} not between {$waParent}.{$lft} and {$waParent}.{$rgt}")
->orWhereRaw("{$waChild}.{$lft} between {$waInterm}.{$lft} and {$waInterm}.{$rgt}")
->whereRaw("{$waInterm}.{$lft} between {$waParent}.{$lft} and {$waParent}.{$rgt}");
});
$this->model->applyNestedSetScope($query, $parentAlias);
$this->model->applyNestedSetScope($query, $intermAlias);
return $query;
}
/**
* @return $this
*/
protected function getMissingParentQuery()
{
return $this->model
->newNestedSetQuery()
->toBase()
->whereNested(function (BaseQueryBuilder $inner) {
$grammar = $this->query->getGrammar();
$table = $this->wrappedTable();
$keyName = $this->wrappedKey();
$parentIdName = $grammar->wrap($this->model->getParentIdName());
$alias = 'p';
$wrappedAlias = $grammar->wrapTable($alias);
$existsCheck = $this->model
->newNestedSetQuery()
->toBase()
->selectRaw('1')
->from($this->query->raw("{$table} as {$wrappedAlias}"))
->whereRaw("{$table}.{$parentIdName} = {$wrappedAlias}.{$keyName}")
->limit(1);
$this->model->applyNestedSetScope($existsCheck, $alias);
$inner->whereRaw("{$parentIdName} is not null")
->addWhereExistsQuery($existsCheck, 'and', true);
});
}
/**
* Get the number of total errors of the tree.
*
* @since 2.0
*
* @return int
*/
public function getTotalErrors()
{
return array_sum($this->countErrors());
}
/**
* Get whether the tree is broken.
*
* @since 2.0
*
* @return bool
*/
public function isBroken()
{
return $this->getTotalErrors() > 0;
}
/**
* Fixes the tree based on parentage info.
*
* Nodes with invalid parent are saved as roots.
*
* @param null|NodeTrait|Model $root
*
* @return int The number of changed nodes
*/
public function fixTree($root = null)
{
$columns = [
$this->model->getKeyName(),
$this->model->getParentIdName(),
$this->model->getLftName(),
$this->model->getRgtName(),
];
$dictionary = $this->model
->newNestedSetQuery()
->when($root, function (self $query) use ($root) {
return $query->whereDescendantOf($root);
})
->defaultOrder()
->get($columns)
->groupBy($this->model->getParentIdName())
->all();
return $this->fixNodes($dictionary, $root);
}
/**
* @param NodeTrait|Model $root
*
* @return int
*/
public function fixSubtree($root)
{
return $this->fixTree($root);
}
/**
* @param array $dictionary
* @param NodeTrait|Model|null $parent
*
* @return int
*/
protected function fixNodes(array &$dictionary, $parent = null)
{
$parentId = $parent ? $parent->getKey() : null;
$cut = $parent ? $parent->getLft() + 1 : 1;
$updated = [];
$moved = 0;
$cut = self::reorderNodes($dictionary, $updated, $parentId, $cut);
// Save nodes that have invalid parent as roots
while ( ! empty($dictionary)) {
$dictionary[null] = reset($dictionary);
unset($dictionary[key($dictionary)]);
$cut = self::reorderNodes($dictionary, $updated, $parentId, $cut);
}
if ($parent && ($grown = $cut - $parent->getRgt()) != 0) {
$moved = $this->model->newScopedQuery()->makeGap($parent->getRgt() + 1, $grown);
$updated[] = $parent->rawNode($parent->getLft(), $cut, $parent->getParentId());
}
foreach ($updated as $model) {
$model->save();
}
return count($updated) + $moved;
}
/**
* @param array $dictionary
* @param array $updated
* @param $parentId
* @param int $cut
*
* @return int
* @internal param int $fixed
*/
protected static function reorderNodes(
array &$dictionary, array &$updated, $parentId = null, $cut = 1
) {
if ( ! isset($dictionary[$parentId])) {
return $cut;
}
/** @var Model|NodeTrait $model */
foreach ($dictionary[$parentId] as $model) {
$lft = $cut;
$cut = self::reorderNodes($dictionary, $updated, $model->getKey(), $cut + 1);
if ($model->rawNode($lft, $cut, $parentId)->isDirty()) {
$updated[] = $model;
}
++$cut;
}
unset($dictionary[$parentId]);
return $cut;
}
/**
* Rebuild the tree based on raw data.
*
* If item data does not contain primary key, new node will be created.
*
* @param array $data
* @param bool $delete Whether to delete nodes that exists but not in the data
* array
* @param null $root
*
* @return int
*/
public function rebuildTree(array $data, $delete = false, $root = null)
{
if ($this->model->usesSoftDelete()) {
$this->withTrashed();
}
$existing = $this
->when($root, function (self $query) use ($root) {
return $query->whereDescendantOf($root);
})
->get()
->getDictionary();
$dictionary = [];
$parentId = $root ? $root->getKey() : null;
$this->buildRebuildDictionary($dictionary, $data, $existing, $parentId);
/** @var Model|NodeTrait $model */
if ( ! empty($existing)) {
if ($delete && ! $this->model->usesSoftDelete()) {
$this->model
->newScopedQuery()
->whereIn($this->model->getKeyName(), array_keys($existing))
->delete();
} else {
foreach ($existing as $model) {
$dictionary[$model->getParentId()][] = $model;
if ($delete && $this->model->usesSoftDelete() &&
! $model->{$model->getDeletedAtColumn()}
) {