/
TreeBehavior.php
297 lines (247 loc) · 7.51 KB
/
TreeBehavior.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
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since CakePHP(tm) v 3.0.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
namespace Cake\Model\Behavior;
use ArrayObject;
use Cake\Collection\Collection;
use Cake\Database\Expression\QueryExpression;
use Cake\Event\Event;
use Cake\ORM\Behavior;
use Cake\ORM\Entity;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
class TreeBehavior extends Behavior {
/**
* Table instance
*
* @var \Cake\ORM\Table
*/
protected $_table;
/**
* Default config
*
* These are merged with user-provided configuration when the behavior is used.
*
* @var array
*/
protected static $_defaultConfig = [
'implementedFinders' => ['path' => 'findPath'],
'parent' => 'parent_id',
'left' => 'lft',
'right' => 'rght',
'scope' => null
];
/**
* Constructor
*
* @param Table $table The table this behavior is attached to.
* @param array $config The config for this behavior.
*/
public function __construct(Table $table, array $config = []) {
parent::__construct($table, $config);
$this->_table = $table;
}
public function findPath($query, $options) {
if (empty($options['for'])) {
throw new \InvalidArgumentException("The 'for' key is required for find('path')");
}
$config = $this->config();
list($left, $right) = [$config['left'], $config['right']];
$node = $this->_table->get($options['for'], ['fields' => [$left, $right]]);
return $this->_scope($query)
->where([
"$left <=" => $node->get($left),
"$right >=" => $node->get($right)
]);
}
/**
* Get the number of child nodes.
*
* @param integer|string $id The ID of the record to read
* @param boolean $direct whether to count direct, or all, children
* @return integer Number of child nodes.
*/
public function childCount($id, $direct = false) {
$config = $this->config();
list($parent, $left, $right) = [$config['parent'], $config['left'], $config['right']];
if ($direct) {
$count = $this->_table->find()
->where([$parent => $id])
->count();
return $count;
}
$node = $this->_table->get($id, [$this->_table->primaryKey() => $id]);
return ($node->{$right} - $node->{$left} - 1) / 2;
}
/**
* Get the child nodes of the current model
*
* If the direct parameter is set to true, only the direct children are returned (based upon the parent_id field)
* If false is passed for the id parameter, top level, or all (depending on direct parameter appropriate) are counted.
*
* @param integer|string $id The ID of the record to read
* @param boolean $direct whether to return only the direct, or all, children
* @param string|array $fields Either a single string of a field name, or an array of field names
* @param array $order SQL ORDER BY conditions (e.g. ['price' => 'DESC']) defaults to the tree order
* @param integer $limit SQL LIMIT clause, for calculating items per page.
* @param integer $page Page number, for accessing paged data
* @return array Array of child nodes
*/
public function children($id, $direct = false, $fields = [], $order = [], $limit = null, $page = 1) {
extract($this->config());
$primaryKey = $this->_table->primaryKey();
if ($direct) {
return $this->_scope($this->_table->find())
->where([$parent => $id])
->all();
}
$node = $this->_scope($this->_table->find())
->select([$right, $left])
->where([$primaryKey => $id])
->first();
if (!$node) {
return false;
}
$order = !$order ? [$left => 'ASC'] : $order;
$query = $this->_scope($this->_table->find());
if ($fields) {
$query->select($fields);
}
$query->where([
"{$right} <" => $node->{$right},
"{$left} >" => $node->{$left}
]);
if ($limit) {
$query->limit($limit);
}
if ($page) {
$query->page($page);
}
return $query->order($order)->all();
}
/**
* Reorder the node without changing the parent.
*
* If the node is the first child, or is a top level node with no previous node this method will return false
*
* @param integer|string $id The ID of the record to move
* @param integer|boolean $number how many places to move the node, or true to move to first position
* @return boolean true on success, false on failure
*/
public function moveUp($id, $number = 1) {
$primaryKey = $this->_table->primaryKey();
$config = $this->config();
extract($config);
if (!$number) {
return false;
}
$node = $this->_scope($this->_table->find())
->select([$primaryKey, $parent, $left, $right])
->where([$primaryKey => $id])
->first();
if ($node->{$parent}) {
$parentNode = $this->_scope($this->_table->find())
->select([$primaryKey, $left, $right])
->where([$primaryKey => $node->{$parent}])
->first();
if (($node->{$left} - 1) == $parentNode->{$left}) {
return false;
}
}
$previousNode = $this->_scope($this->_table->find())
->select([$primaryKey, $left, $right])
->where([$right => ($node->{$left} - 1)]);
$previousNode = $previousNode->first();
if (!$previousNode) {
return false;
}
$edge = $this->_getMax();
$this->_sync($edge - $previousNode->{$left} + 1, '+', "BETWEEN {$previousNode->{$left}} AND {$previousNode->{$right}}");
$this->_sync($node->{$left} - $previousNode->{$left}, '-', "BETWEEN {$node->{$left}} AND {$node->{$right}}");
$this->_sync($edge - $previousNode->{$left} - ($node->{$right} - $node->{$left}), '-', "> {$edge}");
if (is_int($number)) {
$number--;
}
if ($number) {
$this->moveUp($id, $number);
}
return true;
}
/**
* Get the maximum index value in the table.
*
* @return integer
*/
protected function _getMax() {
return $this->_getMaxOrMin('max');
}
/**
* Get the minimum index value in the table.
*
* @return integer
*/
protected function _getMin() {
return $this->_getMaxOrMin('min');
}
/**
* Get the maximum|minimum index value in the table.
*
* @param string $maxOrMin Either 'max' or 'min'
* @return integer
*/
protected function _getMaxOrMin($maxOrMin = 'max') {
extract($this->config());
$LorR = $maxOrMin === 'max' ? $right : $left;
$DorA = $maxOrMin === 'max' ? 'DESC' : 'ASC';
$edge = $this->_scope($this->_table->find())
->select([$LorR])
->order([$LorR => $DorA])
->first();
if (empty($edge->{$LorR})) {
return 0;
}
return $edge->{$LorR};
}
protected function _sync($shift, $dir = '+', $conditions = null, $field = 'both') {
extract($this->config());
if ($field === 'both') {
$this->_sync($shift, $dir, $conditions, $left);
$field = $right;
}
// updateAll + scope
$exp = new QueryExpression();
$exp->add("{$field} = ({$field} {$dir} {$shift})");
$query = $this->_scope($this->_table->query());
$query->update()
->set($exp);
if ($conditions) {
$conditions = "{$field} {$conditions}";
$query->where($conditions);
}
$statement = $query->execute();
$success = $statement->rowCount() > 0;
return $success;
}
protected function _scope($query) {
$config = $this->config();
if (empty($config['scope'])) {
return $query;
} elseif (is_array($config['scope'])) {
return $query->where($config['scope']);
} elseif (is_callable($config['scope'])) {
return $config['scope']($query);
}
return $query;
}
}