-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathNetCommonsTreeBehavior.php
More file actions
1425 lines (1267 loc) · 42.9 KB
/
NetCommonsTreeBehavior.php
File metadata and controls
1425 lines (1267 loc) · 42.9 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
/**
* NetCommons用TreeBehavior
*
* @author Noriko Arai <arai@nii.ac.jp>
* @author Shohei Nakajima <nakajimashouhei@gmail.com>
* @link http://www.netcommons.org NetCommons Project
* @license http://www.netcommons.org/license.txt NetCommons License
* @copyright Copyright 2014, NetCommons Project
*/
App::uses('ModelBehavior', 'Model');
/**
* NetCommons用TreeBehavior
*
* CakePHPのTreeビヘイビアが大量データにあるとパフォーマンスが悪いので、
* NetCommons用にTreeビヘイビアを改良する
*
* @author Shohei Nakajima <nakajimashouhei@gmail.com>
* @package NetCommons\NetCommons\Model\Befavior
*
* @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
* @SuppressWarnings(PHPMD.ExcessiveClassLength)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class NetCommonsTreeBehavior extends ModelBehavior {
/**
* 桁数
*
* @var array
*/
const NUMBER_OF_DIGITS = '8';
/**
* ソートキーのプレフィクス
*
* @var array
*/
const SORT_KEY_PREFIX = '~';
/**
* ソートキーのプレフィクス
*
* @var array
*/
const SORT_KEY_SEPARATOR = '-';
/**
* Errors
*
* @var array
*/
public $errors = array();
/**
* デフォルト値
*
* @var array
*/
protected $_defaults = array(
'parent' => 'parent_id',
//'left' => 'lft', 'right' => 'rght',
'weight' => 'weight',
'sort_key' => 'sort_key',
'child_count' => 'child_count',
'scope' => '1 = 1', 'recursive' => -1,
//'type' => 'nested',
//'__parentChange' => false
);
/**
* エスケープしたカラム名
*
* @var array
*/
protected $_escapeFields = array(
'id' => null,
'parent' => null,
'sort_key' => null,
'weight' => null,
'child_count' => null,
);
/**
* Used to preserve state between delete callbacks.
*
* @var array
*/
//protected $_deletedRow = array();
/**
* TreeBehaviorのセットアップ
*
* @param Model $model 使用するModel
* @param array $config 設定値
* @return void
*/
public function setup(Model $model, $config = array()) {
$settings = $config + $this->_defaults;
$this->_escapeFields[$model->alias]['id'] =
'`' . $model->alias . '`.`' . $model->primaryKey . '`';
if (isset($settings['parent'])) {
$this->_escapeFields[$model->alias]['parent'] =
'`' . $model->alias . '`.`' . $settings['parent'] . '`';
}
if (isset($settings['weight'])) {
$this->_escapeFields[$model->alias]['weight'] =
'`' . $model->alias . '`.`' . $settings['weight'] . '`';
}
if (isset($settings['sort_key'])) {
$this->_escapeFields[$model->alias]['sort_key'] =
'`' . $model->alias . '`.`' . $settings['sort_key'] . '`';
}
if (isset($settings['child_count'])) {
$this->_escapeFields[$model->alias]['child_count'] =
'`' . $model->alias . '`.`' . $settings['child_count'] . '`';
}
$this->settings[$model->alias] = $settings;
}
/**
* 保存する前に呼び出されるメソッド
*
* parentフィールドが$model->dataに含まれている場合にのみ、
* tree用に$model->dataのweight,child_count,sort_keyをセットし、
* また、親、子をのweight,child_count,sort_keyを更新する。
*
* #### CakePHPのTreeBehaviorと異なる点
* lft,rghtが$model->dataにセットしてあったものをそのまま
*
* @param Model $model 呼び出し元のModel
* @param array $options Model::save()から渡されるオプション
* @return bool
* @see Model::save()
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function beforeSave(Model $model, $options = array()) {
$settings = $this->settings[$model->alias];
$escapeFields = $this->_escapeFields[$model->alias];
$weightField = $settings['weight'];
$sortKeyField = $settings['sort_key'];
$childCountField = $settings['child_count'];
$parentField = $settings['parent'];
$parentIsSet = array_key_exists($parentField, $model->data[$model->alias]);
if (! $parentIsSet) {
return true;
}
$parentId = $model->data[$model->alias][$parentField];
if (! $model->id) {
$created = true;
} else {
$target = $this->_getById($model, $model->id);
$created = !(bool)$target;
}
if ($created) {
//新規データの場合
//・親データ取得
if ($model->data[$model->alias][$parentField]) {
$parentNode = $this->_getById($model, $parentId);
if (! $parentNode) {
return false;
}
$parentSortKey = $parentNode[$model->alias]['sort_key'];
} else {
$parentSortKey = null;
}
//・対象のレコードのweight,sort_keyをセットする
$model->data[$model->alias][$childCountField] = 0;
$weight = $this->_getMaxWeight($model, $parentId) + 1;
$model->data[$model->alias][$weightField] = $weight;
$sortKey = $this->_convertWeightToSortKey($weight, $parentSortKey, true);
$model->data[$model->alias][$sortKeyField] = $sortKey;
//・移動先の親のchild_countを増やす
$this->_updateParentCount($model, $sortKey, 1);
} else {
//既存データの場合
$this->_addToWhitelist($model, [$parentField, $weightField, $sortKeyField, $childCountField]);
if ($model->data[$model->alias][$parentField] !== $target[$model->alias][$parentField]) {
//親IDが異なる場合、移動するので、各weightやsort_keyの振り直し
$targetChildCount = $target[$model->alias][$childCountField] + 1;
$childIds = $this->_getChildIds($model, $target);
//・移動先のIDが自分の子供(入れ子になる)の場合、falseを返す。
if (in_array($parentId, $childIds, true)) {
return false;
}
//・既存の親のchild_countを減らす
$this->_updateParentCount(
$model,
$target[$model->alias][$sortKeyField], -1 * $targetChildCount
);
//・番号を詰める処理を実行
$from = $target[$model->alias][$settings['weight']] + 1;
$to = null;
$order = $escapeFields['weight'] . ' asc';
$incrementNumber = -1;
$this->_incrementWeight(
$model, $target[$model->alias][$settings['parent']], $order, $from, $to, $incrementNumber
);
//・移動先の親データ取得
if ($model->data[$model->alias][$parentField]) {
$parentNode = $this->_getById($model, $parentId);
if (! $parentNode) {
return false;
}
$parentSortKey = $parentNode[$model->alias]['sort_key'];
} else {
$parentSortKey = null;
}
//・対象のレコードのweight,sort_keyをセットする
$weight = $this->_getMaxWeight($model, $parentId) + 1;
$model->data[$model->alias][$weightField] = $weight;
$sortKey = $this->_convertWeightToSortKey($weight, $parentSortKey, true);
$model->data[$model->alias][$sortKeyField] = $sortKey;
//・対象の子たちのsort_keyを更新する
$this->_replaceChildSortKey(
$model,
$target[$model->alias][$settings['sort_key']],
$sortKey,
[$escapeFields['id'] => $childIds]
);
//・移動先の親のchild_countを増やす
$this->_updateParentCount(
$model, $sortKey, $targetChildCount,
[$escapeFields['id'] . ' !=' => $target[$model->alias][$model->primaryKey]]
);
}
}
return true;
}
/**
* Stores the record about to be deleted.
*
* This is used to delete child nodes in the afterDelete.
*
* @param Model $model Model using this behavior.
* @param bool $cascade If true records that depend on this record will also be deleted
* @return bool
* @SuppressWarnings(PHPMD.BooleanArgumentFlag)
*/
public function beforeDelete(Model $model, $cascade = true) {
$this->_deletedRow = $this->_getById($model, $model->id);
return true;
}
/**
* After delete method.
*
* Will delete the current node and all children using the deleteAll method and sync the table
*
* @param Model $model Model using this behavior
* @return bool true to continue, false to abort the delete
* @throws InternalErrorException
*/
public function afterDelete(Model $model) {
$settings = $this->settings[$model->alias];
$escapeFields = $this->_escapeFields[$model->alias];
$target = $this->_deletedRow;
$this->_deletedRow[$model->alias] = null;
//対象の子たちを削除する
if ($target[$model->alias][$settings['child_count']] > 0) {
$conditions = [
$settings['scope'],
$escapeFields['sort_key'] . ' LIKE' =>
$target[$model->alias][$settings['sort_key']] . self::SORT_KEY_SEPARATOR . '%'
];
$model->unbindModel(['belongsTo' => array_keys($model->belongsTo)]);
if (! $model->deleteAll($conditions, false, false)) {
throw new InternalErrorException(__d('net_commons', 'Internal Server Error'));
}
$model->resetAssociations();
}
//親のchild_countを減らす
$this->_updateParentCount(
$model,
$target[$model->alias][$settings['sort_key']],
-1 * ($target[$model->alias][$settings['child_count']] + 1)
);
//番号を詰める処理を実行
$from = $target[$model->alias][$settings['weight']] + 1;
$to = null;
$order = $escapeFields['weight'] . ' asc';
$incrementNumber = -1;
$this->_incrementWeight(
$model, $target[$model->alias][$settings['parent']], $order, $from, $to, $incrementNumber
);
return true;
}
/**
* 指定した親IDの最大weightを取得する
*
* @param Model $model 呼び出し元のModel
* @param int|string $parentId 親ID
* @return int
*/
protected function _getMaxWeight(Model $model, $parentId) {
$escapeFields = $this->_escapeFields[$model->alias];
$result = $model->find('first', array(
'recursive' => -1,
'fields' => 'MAX(' . $escapeFields['weight'] . ')',
'conditions' => [
$escapeFields['parent'] => $parentId,
],
));
if (! $result) {
$maxValue = 0;
} else {
$maxValue = array_shift($result[0]);
}
return $maxValue;
}
/**
* weightからsort_keyに変換する
*
* @param int $weight 順序
* @param string|bool $sortKey ソートキー
* @param bool $setKeyIsParent 第二引数の$sortKeyが親を指定しているか否か
* @return string
* @SuppressWarnings(PHPMD.BooleanArgumentFlag)
*/
protected function _convertWeightToSortKey($weight, $sortKey = false, $setKeyIsParent = false) {
if ($sortKey) {
if ($setKeyIsParent) {
$parentKey = $sortKey . self::SORT_KEY_SEPARATOR;
} else {
$parentKey = substr($sortKey, 0, -1 * self::NUMBER_OF_DIGITS);
}
} else {
$parentKey = self::SORT_KEY_PREFIX;
}
return $parentKey . sprintf('%0' . self::NUMBER_OF_DIGITS . 'd', (int)$weight);
}
/**
* 指定した親のchild_countをカウントUp(Down)する
*
* @param Model $model 呼び出し元のModel
* @param string $sortKey ソートキー
* @param int $number カウントUP値
* @param array $addConditions 取得する追加条件
* @return bool
* @throws InternalErrorException
*/
protected function _updateParentCount(Model $model, $sortKey, $number, $addConditions = []) {
$settings = $this->settings[$model->alias];
$escapeFields = $this->_escapeFields[$model->alias];
$sortKeys = explode(self::SORT_KEY_SEPARATOR, $sortKey);
array_pop($sortKeys);
if (! $sortKeys) {
return true;
}
$conditions = [
$settings['scope'],
$escapeFields['sort_key'] => [],
] + $addConditions;
$sort = '';
foreach ($sortKeys as $key) {
if (! $sort) {
$sort = $key;
} else {
$sort .= self::SORT_KEY_SEPARATOR . $key;
}
$conditions[$escapeFields['sort_key']][] = $sort;
}
$update = [
$escapeFields['child_count'] => $escapeFields['child_count'] . ' + (' . $number . ')'
];
$model->unbindModel(['belongsTo' => array_keys($model->belongsTo)]);
if (! $model->updateAll($update, $conditions)) {
throw new InternalErrorException(__d('net_commons', 'Internal Server Error'));
}
$model->resetAssociations();
return true;
}
/**
* 指定したsort_keyを持つ子たちを新しいsort_keyに変更する
*
* @param Model $model 呼び出し元のModel
* @param string $sortKey ソートキー
* @param string $updateSortKey 更新するソートキー
* @param array $conditions 条件配列
* @return bool
* @throws InternalErrorException
*/
protected function _replaceChildSortKey(Model $model, $sortKey, $updateSortKey, $conditions) {
$escapeFields = $this->_escapeFields[$model->alias];
$update = [
$escapeFields['sort_key'] => sprintf(
"REPLACE(" . $escapeFields['sort_key'] . ", '%s', '%s')",
$sortKey,
$updateSortKey
),
];
$model->unbindModel(['belongsTo' => array_keys($model->belongsTo)]);
if (! $model->updateAll($update, $conditions)) {
throw new InternalErrorException(__d('net_commons', 'Internal Server Error'));
}
$model->resetAssociations();
return true;
}
/**
* 指定した親IDの最大weightを取得する
*
* @param Model $model 呼び出し元のModel
* @param int|string $parentId 親ID
* @param string $order SQLのorder by
* @param int $from SQLのBETWEENのFrom
* @param int|null $to SQLのBETWEENのTo。nullの場合、$from以降全て
* @param int $number インクリメントする値
* @return int
* @throws InternalErrorException
*/
protected function _incrementWeight(Model $model, $parentId, $order, $from, $to, $number) {
$settings = $this->settings[$model->alias];
$escapeFields = $this->_escapeFields[$model->alias];
$fields = [
$escapeFields['id'],
$escapeFields['parent'],
$escapeFields['weight'],
$escapeFields['sort_key'],
$escapeFields['child_count']
];
if (is_null($to)) {
$conditions = [
$escapeFields['parent'] => $parentId,
$escapeFields['weight'] . ' >=' => $from
];
} else {
$conditions = [
$escapeFields['parent'] => $parentId,
sprintf($escapeFields['weight'] . ' BETWEEN %s AND %s', (int)$from, (int)$to)
];
}
$incrementRows = $model->find('all', array(
'recursive' => -1,
'fields' => $fields,
'conditions' => $conditions,
'order' => $order,
));
foreach ($incrementRows as $incrementRow) {
$updateWeight = $incrementRow[$model->alias][$settings['weight']] + $number;
$updateSortKey = $this->_convertWeightToSortKey(
$updateWeight,
$incrementRow[$model->alias][$settings['sort_key']],
false
);
if ($incrementRow[$model->alias][$settings['child_count']] > 0) {
//詰めるデータの子たちのsort_keyを更新する
$conditions = [
$escapeFields['sort_key'] . ' LIKE' =>
$incrementRow[$model->alias][$settings['sort_key']] . self::SORT_KEY_SEPARATOR . '%'
];
$this->_replaceChildSortKey(
$model,
$incrementRow[$model->alias][$settings['sort_key']],
$updateSortKey,
$conditions
);
}
//番号を詰める
$update = [
$escapeFields['weight'] => $updateWeight,
$escapeFields['sort_key'] => "'" . $updateSortKey . "'",
];
$conditions = [
$escapeFields['id'] => $incrementRow[$model->alias][$model->primaryKey]
];
$model->unbindModel(['belongsTo' => array_keys($model->belongsTo)]);
if (! $model->updateAll($update, $conditions)) {
throw new InternalErrorException(__d('net_commons', 'Internal Server Error'));
}
$model->resetAssociations();
}
return true;
}
/**
* データを取得するメソッド
*
* @param Model $model 呼び出し元のModel
* @param int|string $id 取得するID
* @return array|bool
*/
protected function _getById(Model $model, $id) {
$settings = $this->settings[$model->alias];
$escapeFields = $this->_escapeFields[$model->alias];
$fields = [
$escapeFields['id'],
$escapeFields['parent'],
$escapeFields['weight'],
$escapeFields['sort_key'],
$escapeFields['child_count']
];
return $model->find('first', array(
'recursive' => $settings['recursive'],
'fields' => $fields,
'conditions' => [$escapeFields['id'] => $id],
'order' => false,
));
}
/**
* データを取得するメソッド
*
* @param Model $model 呼び出し元のModel
* @param array $target 対象のデータ
* @return array
*/
protected function _getChildIds(Model $model, $target) {
$settings = $this->settings[$model->alias];
$escapeFields = $this->_escapeFields[$model->alias];
$childIds = [];
if ($target[$model->alias][$settings['child_count']] > 0) {
$children = $model->find('all', array(
'recursive' => -1,
'fields' => [$model->primaryKey],
'conditions' => [
$escapeFields['sort_key'] . ' LIKE' =>
$target[$model->alias][$settings['sort_key']] . self::SORT_KEY_SEPARATOR . '%'
],
));
foreach ($children as $child) {
if (! in_array($child[$model->alias][$model->primaryKey], $childIds, true)) {
$childIds[] = $child[$model->alias][$model->primaryKey];
}
}
}
return $childIds;
}
/**
* 連想配列の場合、$argからデフォルトのfind()オプションを作成するメソッド
*
* @param array $arg Array
* @return array Options array
*/
protected function _getOptions($arg) {
return count(array_filter(array_keys($arg), 'is_string')) > 0 ?
$arg :
array();
}
/**
* 子ノードの数を取得するメソッド
*
* children メソッドと同様に、 childCount には列の主キー (id) の値を 渡します。
* これにより主キーが指定されたノードの子の数が返されます。オプションの 第二引数では、
* 直下の子ノードのみの数を返すか否かを定義できます。
*
* @param Model $model 呼び出し元のModel
* @param int|string|bool $id 検索するためのレコードのID
* @param bool $direct 直下のノードのみを返すために true を設定します
* @return int 指定されたノードの子の数
* @link https://book.cakephp.org/2.0/ja/core-libraries/behaviors/tree.html#TreeBehavior::childCount
* @SuppressWarnings(PHPMD.BooleanArgumentFlag)
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function childCount(Model $model, $id = null, $direct = false) {
if (is_array($id)) {
extract(array_merge(['id' => null], $id));
}
if ($id === null && $model->id) {
$id = $model->id;
} elseif (! $id) {
$id = null;
}
$settings = $this->settings[$model->alias];
$escapeFields = $this->_escapeFields[$model->alias];
if ($direct) {
return $model->find('count', [
'recursive' => -1,
'conditions' => [
$settings['scope'],
$escapeFields['parent'] => $id
]
]);
}
if ($id === null) {
return $model->find('count', [
'recursive' => -1,
'conditions' => $settings['scope'],
]);
} elseif ($model->id === $id &&
isset($model->data[$model->alias][$settings['child_count']])) {
return $model->data[$model->alias][$settings['child_count']];
} else {
$data = $model->find('first', [
'recursive' => -1,
'fields' => [$model->primaryKey, $settings['child_count']],
'conditions' => [
$settings['scope'],
$model->primaryKey => $id
]
]);
if (! $data) {
return 0;
} else {
return $data[$model->alias][$settings['child_count']];
}
}
}
/**
* 列の主キー(id)の値を用いて、そのアイテムの子を返すメソッド
*
* メソッドは列の主キー(id)の値を用いて、そのアイテムの子を返します。 デフォルトの順番はツリーに出現した順です。
* 第二引数はオプションのパラメータで、 直下の子ノードのみを返すか否かを定義します。
*
* #### CakePHPのTreeBehaviorと異なる点
* $limit, $pageについては、CakePHPのTreeBehaviorでは、取得するデータ全体に対するものであるが、
* 本メソッドでは、子に対するものとする。
*
* @param Model $model 呼び出し元のModel
* @param int|string $id 検索するためのレコードのID
* @param bool $direct 直下のノードのみを返すために true を設定します
* @param string|array $fields 戻り値に含まれるフィールド名の文字列またはフィールドの配列
* @param string $order ORDER BY の SQL 文字列
* @param int $limit SQL の LIMIT 構文
* @param int $page ページつけられた結果にアクセスするための引数
* @param int $recursive 再帰的に関連付けられたモデルの深さのレベル数
* @return array アイテムの子のデータ
* @link https://book.cakephp.org/2.0/ja/core-libraries/behaviors/tree.html#TreeBehavior::children
* @SuppressWarnings(PHPMD.BooleanArgumentFlag)
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function children(Model $model, $id = null, $direct = false, $fields = null,
$order = null, $limit = null, $page = 1, $recursive = null) {
$options = array();
if (is_array($id)) {
$options = $this->_getOptions($id);
extract(array_merge(array('id' => null), $id));
}
if ($id === null && $model->id) {
$id = $model->id;
} elseif (!$id) {
$id = null;
}
$parentId = $id;
$settings = $this->settings[$model->alias];
$escapeFields = $this->_escapeFields[$model->alias];
if (is_null($recursive)) {
$recursive = $settings['recursive'];
}
if (! $order) {
$order = [
$escapeFields['sort_key'] . ' asc',
];
}
if ($direct) {
$conditions = [
$settings['scope'],
$escapeFields['parent'] => $parentId
];
return $model->find(
'all',
compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive')
);
}
if (! $parentId) {
$conditions = $settings['scope'];
} else {
$current = $model->find('first', [
'recursive' => -1,
'fields' => [$settings['sort_key']],
'conditions' => [
$model->primaryKey => $parentId
],
]);
$conditions = [
$settings['scope'],
$escapeFields['sort_key'] . ' LIKE' =>
$current[$model->alias][$settings['sort_key']] . self::SORT_KEY_SEPARATOR . '%'
];
}
$options = array_merge(
compact('conditions', 'fields', 'order', 'limit', 'page', 'recursive'),
$options
);
return $model->find('all', $options);
}
/**
* spacer オプションで指定された ネストしたプレフィックスをつけて find(『list』) と似たデータを返すメソッド
*
* 独自のfind()呼び出しを使用する場合、generateTreeList()を直接使用するのと同じ結果を生成するために、
* "sort_key asc"でソートする必要があることに注意してください。
*
* オプション($options):
*
* - 'keyPath': キーの文字列パス。例: 「{n}.Post.id」
* - 'valuePath': 値の文字列パス。例: 「{n}.Post.title」
* - 'spacer': 繰り返しの文字または文字列
*
* @param Model $model 呼び出し元のModel
* @param array $results find(『all』) の実行結果
* @param array $options 設定するオプション配列
* @return array
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function formatTreeList(Model $model, $results, $options = array()) {
if (empty($results)) {
return array();
}
$defaults = array(
'keyPath' => null,
'valuePath' => null,
'spacer' => '_'
);
$options += $defaults;
$settings = $this->settings[$model->alias];
if (!$options['keyPath']) {
$options['keyPath'] = '{n}.' . $model->alias . '.' . $model->primaryKey;
}
list(, $keyModel, $keyField) = explode('.', $options['keyPath']);
if (!$options['valuePath']) {
$options['valuePath'] = '{n}.' . $model->alias . '.' . $model->displayField;
}
list(, $valueModel, $valueField) = explode('.', $options['valuePath']);
$resultsList = [];
$level = 0;
$levelStack = [];
foreach ($results as $i => $row) {
if (isset($row[$keyModel]) && isset($row[$keyModel][$keyField])) {
$key = $row[$keyModel][$keyField];
} else {
$key = $row[$model->alias][$model->primaryKey];
}
if (isset($row[$valueModel]) && isset($row[$valueModel][$valueField])) {
$value = $row[$valueModel][$valueField];
} else {
$value = $row[$model->alias][$model->displayField];
}
$resultsList[$key] = str_repeat($options['spacer'], $level) . $value;
if (isset($results[$i + 1])) {
$next = $results[$i + 1];
$parentField = $settings['parent'];
if ($row[$model->alias][$model->primaryKey] === $next[$model->alias][$parentField]) {
$levelStack[$row[$model->alias][$model->primaryKey]] = $level;
$level++;
} elseif (isset($levelStack[$next[$model->alias][$parentField]])) {
$level = $levelStack[$next[$model->alias][$parentField]] + 1;
} else {
$levelStack[$row[$model->alias][$model->primaryKey]] = $level;
$level = 0;
}
}
}
return $resultsList;
}
/**
* spacerオプションで指定したプレフィックスでインデントを付け構造が分かるようにした find(『list』) に似たデータを返すメソッド
*
* #### CakePHPのTreeBehaviorと異なる点
*
* $keyPathと$valuePathは、複雑なものには対応しない。必ず、{n}.Post.idのような構成にすること。
*
* @param Model $model 呼び出し元のModel
* @param string|array $conditions find()と同様の検索条件オプションに使用
* @param string $keyPath キーとして使用するフィールドのパス。例: 「{n}.Post.id」
* @param string $valuePath ラベルに使用するフィールドのパス。例: 「{n}.Post.title」
* @param string $spacer 各々の値の前に付ける深さを示すための文字列
* @param int $recursive 関連付けられたレコードを取得する際の深さのレベル数
* @return array
* @link https://book.cakephp.org/2.0/ja/core-libraries/behaviors/tree.html#TreeBehavior::generateTreeList
*/
public function generateTreeList(Model $model, $conditions = null, $keyPath = null,
$valuePath = null, $spacer = '_', $recursive = null) {
$settings = $this->settings[$model->alias];
$escapeFields = $this->_escapeFields[$model->alias];
if (is_null($recursive)) {
$recursive = $settings['recursive'];
}
$fields = null;
if (!$keyPath && !$valuePath && $model->hasField($model->displayField)) {
$fields = [
$model->primaryKey, $model->displayField, $settings['parent'],
];
} else {
$fields = [
substr($keyPath, 4), substr($valuePath, 4), $model->primaryKey, $settings['parent'],
];
}
$conditions = (array)$conditions;
if ($settings['scope']) {
$conditions[] = $settings['scope'];
}
$order = [
$escapeFields['sort_key'] . ' asc',
];
$results = $model->find('all', compact('conditions', 'fields', 'order', 'recursive'));
return $this->formatTreeList($model, $results, compact('keyPath', 'valuePath', 'spacer'));
}
/**
* 特定のノードのレベルを取得するメソッド
*
* @param Model $model 呼び出し元のModel
* @param int|string|null $id ID
* @return int|bool
* @link https://book.cakephp.org/2.0/ja/core-libraries/behaviors/tree.html#TreeBehavior::getLevel
*/
public function getLevel(Model $model, $id = null) {
if ($id === null) {
$id = $model->id;
}
$settings = $this->settings[$model->alias];
$node = $model->find('first', array(
'recursive' => -1,
'conditions' => [$model->primaryKey => $id],
'fields' => [$settings['sort_key']],
'order' => false,
));
if (empty($node)) {
return false;
}
return substr_count($node[$model->alias][$settings['sort_key']], self::SORT_KEY_SEPARATOR);
}
/**
* 親ノードを返すメソッド
*
* @param Model $model 呼び出し元のModel
* @param int|string $id 読み取るレコードのID
* @param string|array $fields 取得するフィールド
* @param int $recursive 関連付けられたレコードを取得する際の深さのレベル数
* @return array|bool
* @link https://book.cakephp.org/2.0/ja/core-libraries/behaviors/tree.html#TreeBehavior::getParentNode
*/
public function getParentNode(Model $model, $id = null, $fields = null, $recursive = null) {
$options = array();
if (is_array($id)) {
$options = $this->_getOptions($id);
extract(array_merge(array('id' => null), $id));
}
$settings = $this->settings[$model->alias];
$escapeFields = $this->_escapeFields[$model->alias];
if (is_null($recursive)) {
$recursive = $settings['recursive'];
}
$parent = $model->find('first', array(
'recursive' => -1,
'fields' => $escapeFields['parent'],
'conditions' => [$escapeFields['id'] => $id],
'order' => false,
));
if ($parent) {
$parentId = $parent[$model->alias][$settings['parent']];
if (! $parentId) {
return [];
} else {
$options = array_merge(array(
'recursive' => $recursive,
'fields' => $fields,
'conditions' => array($escapeFields['id'] => $parentId),
'order' => false,
), $options);
return $model->find('first', $options);
}
}
return false;
}
/**
* トップのノードからたどって階層化されたデータのパス (path) を返すメソッド
*
* @param Model $model 呼び出し元のModel
* @param int|string|null $id 読み取るレコードのID
* @param string|array|null $fields フィールド名
* @param int|null $recursive 関連付けられたレコードを取得する際の深さのレベル数
* @return array
* @link https://book.cakephp.org/2.0/ja/core-libraries/behaviors/tree.html#TreeBehavior::getPath
*/
public function getPath(Model $model, $id = null, $fields = null, $recursive = null) {
$options = array();
if (is_array($id)) {
$options = $this->_getOptions($id);
extract(array_merge(array('id' => null), $id));
}
if (!empty($options)) {
$fields = null;
if (!empty($options['fields'])) {
$fields = $options['fields'];
}
if (!empty($options['recursive'])) {
$recursive = $options['recursive'];
}
}
$settings = $this->settings[$model->alias];
$escapeFields = $this->_escapeFields[$model->alias];
if (is_null($recursive)) {
$recursive = $settings['recursive'];
}
$result = $model->find('first', array(
'recursive' => $recursive,
'fields' => [$escapeFields['sort_key']],
'conditions' => [$escapeFields['id'] => $id],
'order' => false,
));
if ($result) {
$sortKeys = explode(self::SORT_KEY_SEPARATOR, $result[$model->alias][$settings['sort_key']]);
} else {
return [];
}
$conditions = [
$settings['scope'],
$escapeFields['sort_key'] => [],
];