TreeBehavior.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since CakePHP(tm) v 3.0.0
  13. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  14. */
  15. namespace Cake\Model\Behavior;
  16. use ArrayObject;
  17. use Cake\Collection\Collection;
  18. use Cake\Database\Expression\QueryExpression;
  19. use Cake\Event\Event;
  20. use Cake\ORM\Behavior;
  21. use Cake\ORM\Entity;
  22. use Cake\ORM\Table;
  23. use Cake\ORM\TableRegistry;
  24. class TreeBehavior extends Behavior {
  25. /**
  26. * Table instance
  27. *
  28. * @var \Cake\ORM\Table
  29. */
  30. protected $_table;
  31. /**
  32. * Default config
  33. *
  34. * These are merged with user-provided configuration when the behavior is used.
  35. *
  36. * @var array
  37. */
  38. protected static $_defaultConfig = [
  39. 'implementedFinders' => [
  40. 'path' => 'findPath',
  41. 'children' => 'findChildren',
  42. ],
  43. 'parent' => 'parent_id',
  44. 'left' => 'lft',
  45. 'right' => 'rght',
  46. 'scope' => null
  47. ];
  48. /**
  49. * Constructor
  50. *
  51. * @param Table $table The table this behavior is attached to.
  52. * @param array $config The config for this behavior.
  53. */
  54. public function __construct(Table $table, array $config = []) {
  55. parent::__construct($table, $config);
  56. $this->_table = $table;
  57. }
  58. public function findPath($query, $options) {
  59. if (empty($options['for'])) {
  60. throw new \InvalidArgumentException("The 'for' key is required for find('path')");
  61. }
  62. $config = $this->config();
  63. list($left, $right) = [$config['left'], $config['right']];
  64. $node = $this->_table->get($options['for'], ['fields' => [$left, $right]]);
  65. return $this->_scope($query)
  66. ->where([
  67. "$left <=" => $node->get($left),
  68. "$right >=" => $node->get($right)
  69. ]);
  70. }
  71. /**
  72. * Get the number of child nodes.
  73. *
  74. * @param integer|string $id The ID of the record to read
  75. * @param boolean $direct whether to count direct, or all, children
  76. * @return integer Number of child nodes.
  77. */
  78. public function childCount($id, $direct = false) {
  79. $config = $this->config();
  80. list($parent, $left, $right) = [$config['parent'], $config['left'], $config['right']];
  81. if ($direct) {
  82. $count = $this->_table->find()
  83. ->where([$parent => $id])
  84. ->count();
  85. return $count;
  86. }
  87. $node = $this->_table->get($id, [$this->_table->primaryKey() => $id]);
  88. return ($node->{$right} - $node->{$left} - 1) / 2;
  89. }
  90. /**
  91. * Get the child nodes of the current model
  92. *
  93. * Available options are:
  94. *
  95. * - for: The ID of the record to read.
  96. * - direct: Boolean, whether to return only the direct (true), or all (false), children. default to false (all children).
  97. *
  98. * If the direct option is set to true, only the direct children are returned (based upon the parent_id field)
  99. * If false is passed for the id parameter, top level, or all (depending on direct parameter appropriate) are counted.
  100. *
  101. * @param array $options Array of options as described above
  102. * @return \Cake\ORM\Query
  103. * @throws \Cake\ORM\Error\RecordNotFoundException When node was not found
  104. * @throws \InvalidArgumentException When the 'for' key is not passed in $options
  105. */
  106. public function findChildren($query, $options) {
  107. extract($this->config());
  108. extract($options);
  109. $primaryKey = $this->_table->primaryKey();
  110. $direct = !isset($direct) ? false : $direct;
  111. if (empty($for)) {
  112. throw new \InvalidArgumentException("The 'for' key is required for find('children')");
  113. }
  114. if ($query->clause('order') === null) {
  115. $query->order([$left => 'ASC']);
  116. }
  117. if ($direct) {
  118. return $this->_scope($query)->where([$parent => $for]);
  119. }
  120. $node = $this->_scope($this->_table->find())
  121. ->select([$right, $left])
  122. ->where([$primaryKey => $for])
  123. ->first();
  124. if (!$node) {
  125. throw new \Cake\ORM\Error\RecordNotFoundException("Node \"{$for}\ was not found in the tree.");
  126. }
  127. return $this->_scope($query)
  128. ->where([
  129. "{$right} <" => $node->{$right},
  130. "{$left} >" => $node->{$left}
  131. ]);
  132. }
  133. /**
  134. * Reorder the node without changing the parent.
  135. *
  136. * If the node is the first child, or is a top level node with no previous node this method will return false
  137. *
  138. * @param integer|string $id The ID of the record to move
  139. * @param integer|boolean $number How many places to move the node, or true to move to first position
  140. * @throws \Cake\ORM\Error\RecordNotFoundException When node was not found
  141. * @return boolean true on success, false on failure
  142. */
  143. public function moveUp($id, $number = 1) {
  144. extract($this->config());
  145. $primaryKey = $this->_table->primaryKey();
  146. if (!$number) {
  147. return false;
  148. }
  149. $node = $this->_scope($this->_table->find())
  150. ->select([$parent, $left, $right])
  151. ->where([$primaryKey => $id])
  152. ->first();
  153. if (!$node) {
  154. throw new \Cake\ORM\Error\RecordNotFoundException("Node \"{$id}\" was not found in the tree.");
  155. }
  156. if ($node->{$parent}) {
  157. $parentNode = $this->_table->get($node->{$parent}, ['fields' => [$left, $right]]);
  158. if (($node->{$left} - 1) == $parentNode->{$left}) {
  159. return false;
  160. }
  161. }
  162. $previousNode = $this->_scope($this->_table->find())
  163. ->select([$left, $right])
  164. ->where([$right => ($node->{$left} - 1)])
  165. ->first();
  166. if (!$previousNode) {
  167. return false;
  168. }
  169. $edge = $this->_getMax();
  170. $this->_sync($edge - $previousNode->{$left} + 1, '+', "BETWEEN {$previousNode->{$left}} AND {$previousNode->{$right}}");
  171. $this->_sync($node->{$left} - $previousNode->{$left}, '-', "BETWEEN {$node->{$left}} AND {$node->{$right}}");
  172. $this->_sync($edge - $previousNode->{$left} - ($node->{$right} - $node->{$left}), '-', "> {$edge}");
  173. if (is_int($number)) {
  174. $number--;
  175. }
  176. if ($number) {
  177. $this->moveUp($id, $number);
  178. }
  179. return true;
  180. }
  181. /**
  182. * Reorder the node without changing the parent.
  183. *
  184. * If the node is the last child, or is a top level node with no subsequent node this method will return false
  185. *
  186. * @param integer|string $id The ID of the record to move
  187. * @param integer|boolean $number How many places to move the node or true to move to last position
  188. * @throws \Cake\ORM\Error\RecordNotFoundException When node was not found
  189. * @return boolean true on success, false on failure
  190. */
  191. public function moveDown($id, $number = 1) {
  192. extract($this->config());
  193. $primaryKey = $this->_table->primaryKey();
  194. if (!$number) {
  195. return false;
  196. }
  197. $node = $this->_scope($this->_table->find())
  198. ->select([$parent, $left, $right])
  199. ->where([$primaryKey => $id])
  200. ->first();
  201. if (!$node) {
  202. throw new \Cake\ORM\Error\RecordNotFoundException("Node \"{$id}\" was not found in the tree.");
  203. }
  204. if ($node->{$parent}) {
  205. $parentNode = $this->_table->get($node->{$parent}, ['fields' => [$left, $right]]);
  206. if (($node->{$right} + 1) == $parentNode->{$right}) {
  207. return false;
  208. }
  209. }
  210. $nextNode = $this->_scope($this->_table->find())
  211. ->select([$left, $right])
  212. ->where([$left => $node->{$right} + 1])
  213. ->first();
  214. if (!$nextNode) {
  215. return false;
  216. }
  217. $edge = $this->_getMax();
  218. $this->_sync($edge - $node->{$left} + 1, '+', "BETWEEN {$node->{$left}} AND {$node->{$right}}");
  219. $this->_sync($nextNode->{$left} - $node->{$left}, '-', "BETWEEN {$nextNode->{$left}} AND {$nextNode->{$right}}");
  220. $this->_sync($edge - $node->{$left} - ($nextNode->{$right} - $nextNode->{$left}), '-', "> {$edge}");
  221. if (is_int($number)) {
  222. $number--;
  223. }
  224. if ($number) {
  225. $this->moveDown($id, $number);
  226. }
  227. return true;
  228. }
  229. /**
  230. * Recovers the lft and right column values out of the hirearchy defined by the
  231. * parent column.
  232. *
  233. * @return void
  234. */
  235. public function recover() {
  236. $this->_table->connection()->transactional(function() {
  237. $this->_recoverTree();
  238. });
  239. }
  240. /**
  241. * Recursive method used to recover a single level of the tree
  242. *
  243. * @param integer $counter The Last left column value that was assigned
  244. * @param mixed $parentId the parent id of the level to be recovered
  245. * @return integer Ne next value to use for the left column
  246. */
  247. protected function _recoverTree($counter = 0, $parentId = null) {
  248. $config = $this->config();
  249. list($parent, $left, $right) = [$config['parent'], $config['left'], $config['right']];
  250. $pk = (array)$this->_table->primaryKey();
  251. $query = $this->_scope($this->_table->query())
  252. ->select($pk)
  253. ->where(function($exp) use ($parentId, $parent) {
  254. return $parentId === null ? $exp->isNull($parent) : $exp->eq($parent, $parentId);
  255. })
  256. ->order($pk)
  257. ->hydrate(false)
  258. ->bufferResults(false);
  259. $leftCounter = $counter;
  260. foreach ($query as $row) {
  261. $counter++;
  262. $counter = $this->_recoverTree($counter, $row[$pk[0]]);
  263. }
  264. $this->_table->updateAll(
  265. [$left => $leftCounter, $right => $counter + 1],
  266. [$pk[0] => $parentId]
  267. );
  268. return $counter + 1;
  269. }
  270. /**
  271. * Get the maximum index value in the table.
  272. *
  273. * @return integer
  274. */
  275. protected function _getMax() {
  276. return $this->_getMaxOrMin('max');
  277. }
  278. /**
  279. * Get the minimum index value in the table.
  280. *
  281. * @return integer
  282. */
  283. protected function _getMin() {
  284. return $this->_getMaxOrMin('min');
  285. }
  286. /**
  287. * Get the maximum|minimum index value in the table.
  288. *
  289. * @param string $maxOrMin Either 'max' or 'min'
  290. * @return integer
  291. */
  292. protected function _getMaxOrMin($maxOrMin = 'max') {
  293. extract($this->config());
  294. $LorR = $maxOrMin === 'max' ? $right : $left;
  295. $DorA = $maxOrMin === 'max' ? 'DESC' : 'ASC';
  296. $edge = $this->_scope($this->_table->find())
  297. ->select([$LorR])
  298. ->order([$LorR => $DorA])
  299. ->first();
  300. if (empty($edge->{$LorR})) {
  301. return 0;
  302. }
  303. return $edge->{$LorR};
  304. }
  305. protected function _sync($shift, $dir = '+', $conditions = null, $field = 'both') {
  306. extract($this->config());
  307. if ($field === 'both') {
  308. $this->_sync($shift, $dir, $conditions, $left);
  309. $field = $right;
  310. }
  311. // updateAll + scope
  312. $exp = new QueryExpression();
  313. $exp->add("{$field} = ({$field} {$dir} {$shift})");
  314. $query = $this->_scope($this->_table->query());
  315. $query->update()
  316. ->set($exp);
  317. if ($conditions) {
  318. $conditions = "{$field} {$conditions}";
  319. $query->where($conditions);
  320. }
  321. $statement = $query->execute();
  322. $success = $statement->rowCount() > 0;
  323. return $success;
  324. }
  325. protected function _scope($query) {
  326. $config = $this->config();
  327. if (empty($config['scope'])) {
  328. return $query;
  329. } elseif (is_array($config['scope'])) {
  330. return $query->where($config['scope']);
  331. } elseif (is_callable($config['scope'])) {
  332. return $config['scope']($query);
  333. }
  334. return $query;
  335. }
  336. }