TreeBehavior.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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. /**
  59. * Before save listener.
  60. * Transparently managse setting the lft and rght fields if the parent field is
  61. * included in the parameters to be saved.
  62. *
  63. * @param \Cake\Event\Event the beforeSave event that was fired
  64. * @param \Cake\ORM\Entity the entity that is going to be saved
  65. * @return void
  66. */
  67. public function beforeSave(Event $event, Entity $entity) {
  68. $isNew = $entity->isNew();
  69. $config = $this->config('parent');
  70. $parent = $entity->get($config['parent']);
  71. $primaryKey = (array)$this->_table->primaryKey();
  72. $dirty = $entity->dirty($config['parent']);
  73. if ($isNew && $parent) {
  74. if ($entity->get($primaryKey[0]) == $parent) {
  75. throw new \RuntimeException("Cannot set a node's parent as itself");
  76. }
  77. $parentNode = $this->_getParent($parent);
  78. $edge = $parentNode->get($config['right']);
  79. $entity->set($config['left'], $edge);
  80. $entity->set($config['right'], $edge + 1);
  81. $this->_sync(2, '+', ">= {$edge}");
  82. }
  83. if ($isNew && !$parent) {
  84. $edge = $this->_getMax();
  85. $entity->set($config['left'],$edge + 1);
  86. $entity->set($config['right'], $edge + 2);
  87. }
  88. if (!$isNew && $dirty && $parent) {
  89. $this->_setParent($entity, $parent);
  90. }
  91. }
  92. protected function _getParent($id) {
  93. $config = $this->config();
  94. $primaryKey = (array)$this->_table->primaryKey();
  95. $parentNode = $this->_scope($this->_table->find())
  96. ->select([$config['left'], $config['right']])
  97. ->where([$primaryKey[0] => $id])
  98. ->first();
  99. if (!$parentNode) {
  100. throw new \Cake\ORM\Error\RecordNotFoundException(
  101. "Parent node \"{$parent}\ was not found in the tree."
  102. );
  103. }
  104. return $parentNode;
  105. }
  106. protected function _setParent($entity, $parent) {
  107. $config = $this->config();
  108. $parentNode = $this->_getParent($parent);
  109. $parentNodeLeft = $parentNode->get($config['left']);
  110. $parentNoderight = $parentNode->get($config['right']);
  111. $right = $entity->get($config['right']);
  112. $left = $entity->get($config['left']);
  113. $diff = $right - $left + 1;
  114. $targetLeft = $parentRight - $diff;
  115. $targetRight = $parentRight - 1;
  116. // Values for moving to the left
  117. $min = $parentRight;
  118. $max = $left - 1;
  119. if ($left < $targetLeft) {
  120. //Moving to the right
  121. $min = $right + 1;
  122. $max = $parentRight - 1;
  123. $diff *= -1;
  124. }
  125. $this->_sync($diff, '+', "BETWEEN {$min} AND {$max}");
  126. if ($right - $left > 1) {
  127. //Correcting internal subtree
  128. $internalLeft = $left + 1;
  129. $internalRight = $right - 1;
  130. $this->_sync($targetLeft - $left, '+', "BETWEEN {$internalLeft} AND {$internalRight}");
  131. }
  132. //Allocating new position
  133. $entity->set($config['left'], $targetLeft);
  134. $entity->set($config['right'], $targetRight);
  135. }
  136. public function findPath($query, $options) {
  137. if (empty($options['for'])) {
  138. throw new \InvalidArgumentException("The 'for' key is required for find('path')");
  139. }
  140. $config = $this->config();
  141. list($left, $right) = [$config['left'], $config['right']];
  142. $node = $this->_table->get($options['for'], ['fields' => [$left, $right]]);
  143. return $this->_scope($query)
  144. ->where([
  145. "$left <=" => $node->get($left),
  146. "$right >=" => $node->get($right)
  147. ]);
  148. }
  149. /**
  150. * Get the number of child nodes.
  151. *
  152. * @param integer|string $id The ID of the record to read
  153. * @param boolean $direct whether to count direct, or all, children
  154. * @return integer Number of child nodes.
  155. */
  156. public function childCount($id, $direct = false) {
  157. $config = $this->config();
  158. list($parent, $left, $right) = [$config['parent'], $config['left'], $config['right']];
  159. if ($direct) {
  160. $count = $this->_table->find()
  161. ->where([$parent => $id])
  162. ->count();
  163. return $count;
  164. }
  165. $node = $this->_table->get($id, [$this->_table->primaryKey() => $id]);
  166. return ($node->{$right} - $node->{$left} - 1) / 2;
  167. }
  168. /**
  169. * Get the child nodes of the current model
  170. *
  171. * Available options are:
  172. *
  173. * - for: The ID of the record to read.
  174. * - direct: Boolean, whether to return only the direct (true), or all (false), children. default to false (all children).
  175. *
  176. * If the direct option is set to true, only the direct children are returned (based upon the parent_id field)
  177. * If false is passed for the id parameter, top level, or all (depending on direct parameter appropriate) are counted.
  178. *
  179. * @param array $options Array of options as described above
  180. * @return \Cake\ORM\Query
  181. * @throws \Cake\ORM\Error\RecordNotFoundException When node was not found
  182. * @throws \InvalidArgumentException When the 'for' key is not passed in $options
  183. */
  184. public function findChildren($query, $options) {
  185. $config = $this->config();
  186. $options += ['for' => null, 'direct' => false];
  187. list($parent, $left, $right) = [$config['parent'], $config['left'], $config['right']];
  188. list($for, $direct) = [$options['for'], $options['direct']];
  189. $primaryKey = $this->_table->primaryKey();
  190. if (empty($for)) {
  191. throw new \InvalidArgumentException("The 'for' key is required for find('children')");
  192. }
  193. if ($query->clause('order') === null) {
  194. $query->order([$left => 'ASC']);
  195. }
  196. if ($direct) {
  197. return $this->_scope($query)->where([$parent => $for]);
  198. }
  199. $node = $this->_scope($this->_table->find())
  200. ->select([$right, $left])
  201. ->where([$primaryKey => $for])
  202. ->first();
  203. if (!$node) {
  204. throw new \Cake\ORM\Error\RecordNotFoundException("Node \"{$for}\ was not found in the tree.");
  205. }
  206. return $this->_scope($query)
  207. ->where([
  208. "{$right} <" => $node->{$right},
  209. "{$left} >" => $node->{$left}
  210. ]);
  211. }
  212. /**
  213. * Reorder the node without changing the parent.
  214. *
  215. * If the node is the first child, or is a top level node with no previous node this method will return false
  216. *
  217. * @param integer|string $id The ID of the record to move
  218. * @param integer|boolean $number How many places to move the node, or true to move to first position
  219. * @throws \Cake\ORM\Error\RecordNotFoundException When node was not found
  220. * @return boolean true on success, false on failure
  221. */
  222. public function moveUp($id, $number = 1) {
  223. $config = $this->config();
  224. list($parent, $left, $right) = [$config['parent'], $config['left'], $config['right']];
  225. $primaryKey = $this->_table->primaryKey();
  226. if (!$number) {
  227. return false;
  228. }
  229. $node = $this->_scope($this->_table->find())
  230. ->select([$parent, $left, $right])
  231. ->where([$primaryKey => $id])
  232. ->first();
  233. if (!$node) {
  234. throw new \Cake\ORM\Error\RecordNotFoundException("Node \"{$id}\" was not found in the tree.");
  235. }
  236. if ($node->{$parent}) {
  237. $parentNode = $this->_table->get($node->{$parent}, ['fields' => [$left, $right]]);
  238. if (($node->{$left} - 1) == $parentNode->{$left}) {
  239. return false;
  240. }
  241. }
  242. $previousNode = $this->_scope($this->_table->find())
  243. ->select([$left, $right])
  244. ->where([$right => ($node->{$left} - 1)])
  245. ->first();
  246. if (!$previousNode) {
  247. return false;
  248. }
  249. $edge = $this->_getMax();
  250. $this->_sync($edge - $previousNode->{$left} + 1, '+', "BETWEEN {$previousNode->{$left}} AND {$previousNode->{$right}}");
  251. $this->_sync($node->{$left} - $previousNode->{$left}, '-', "BETWEEN {$node->{$left}} AND {$node->{$right}}");
  252. $this->_sync($edge - $previousNode->{$left} - ($node->{$right} - $node->{$left}), '-', "> {$edge}");
  253. if (is_int($number)) {
  254. $number--;
  255. }
  256. if ($number) {
  257. $this->moveUp($id, $number);
  258. }
  259. return true;
  260. }
  261. /**
  262. * Reorder the node without changing the parent.
  263. *
  264. * If the node is the last child, or is a top level node with no subsequent node this method will return false
  265. *
  266. * @param integer|string $id The ID of the record to move
  267. * @param integer|boolean $number How many places to move the node or true to move to last position
  268. * @throws \Cake\ORM\Error\RecordNotFoundException When node was not found
  269. * @return boolean true on success, false on failure
  270. */
  271. public function moveDown($id, $number = 1) {
  272. $config = $this->config();
  273. list($parent, $left, $right) = [$config['parent'], $config['left'], $config['right']];
  274. $primaryKey = $this->_table->primaryKey();
  275. if (!$number) {
  276. return false;
  277. }
  278. $node = $this->_scope($this->_table->find())
  279. ->select([$parent, $left, $right])
  280. ->where([$primaryKey => $id])
  281. ->first();
  282. if (!$node) {
  283. throw new \Cake\ORM\Error\RecordNotFoundException("Node \"{$id}\" was not found in the tree.");
  284. }
  285. if ($node->{$parent}) {
  286. $parentNode = $this->_table->get($node->{$parent}, ['fields' => [$left, $right]]);
  287. if (($node->{$right} + 1) == $parentNode->{$right}) {
  288. return false;
  289. }
  290. }
  291. $nextNode = $this->_scope($this->_table->find())
  292. ->select([$left, $right])
  293. ->where([$left => $node->{$right} + 1])
  294. ->first();
  295. if (!$nextNode) {
  296. return false;
  297. }
  298. $edge = $this->_getMax();
  299. $this->_sync($edge - $node->{$left} + 1, '+', "BETWEEN {$node->{$left}} AND {$node->{$right}}");
  300. $this->_sync($nextNode->{$left} - $node->{$left}, '-', "BETWEEN {$nextNode->{$left}} AND {$nextNode->{$right}}");
  301. $this->_sync($edge - $node->{$left} - ($nextNode->{$right} - $nextNode->{$left}), '-', "> {$edge}");
  302. if (is_int($number)) {
  303. $number--;
  304. }
  305. if ($number) {
  306. $this->moveDown($id, $number);
  307. }
  308. return true;
  309. }
  310. /**
  311. * Recovers the lft and right column values out of the hirearchy defined by the
  312. * parent column.
  313. *
  314. * @return void
  315. */
  316. public function recover() {
  317. $this->_table->connection()->transactional(function() {
  318. $this->_recoverTree();
  319. });
  320. }
  321. /**
  322. * Recursive method used to recover a single level of the tree
  323. *
  324. * @param integer $counter The Last left column value that was assigned
  325. * @param mixed $parentId the parent id of the level to be recovered
  326. * @return integer Ne next value to use for the left column
  327. */
  328. protected function _recoverTree($counter = 0, $parentId = null) {
  329. $config = $this->config();
  330. list($parent, $left, $right) = [$config['parent'], $config['left'], $config['right']];
  331. $pk = (array)$this->_table->primaryKey();
  332. $query = $this->_scope($this->_table->query())
  333. ->select($pk)
  334. ->where(function($exp) use ($parentId, $parent) {
  335. return $parentId === null ? $exp->isNull($parent) : $exp->eq($parent, $parentId);
  336. })
  337. ->order($pk)
  338. ->hydrate(false)
  339. ->bufferResults(false);
  340. $leftCounter = $counter;
  341. foreach ($query as $row) {
  342. $counter++;
  343. $counter = $this->_recoverTree($counter, $row[$pk[0]]);
  344. }
  345. if ($parentId === null) {
  346. return $counter;
  347. }
  348. $this->_table->updateAll(
  349. [$left => $leftCounter, $right => $counter + 1],
  350. [$pk[0] => $parentId]
  351. );
  352. return $counter + 1;
  353. }
  354. /**
  355. * Get the maximum index value in the table.
  356. *
  357. * @return integer
  358. */
  359. protected function _getMax() {
  360. return $this->_getMaxOrMin('max');
  361. }
  362. /**
  363. * Get the minimum index value in the table.
  364. *
  365. * @return integer
  366. */
  367. protected function _getMin() {
  368. return $this->_getMaxOrMin('min');
  369. }
  370. /**
  371. * Get the maximum|minimum index value in the table.
  372. *
  373. * @param string $maxOrMin Either 'max' or 'min'
  374. * @return integer
  375. */
  376. protected function _getMaxOrMin($maxOrMin = 'max') {
  377. extract($this->config());
  378. $LorR = $maxOrMin === 'max' ? $right : $left;
  379. $DorA = $maxOrMin === 'max' ? 'DESC' : 'ASC';
  380. $edge = $this->_scope($this->_table->find())
  381. ->select([$LorR])
  382. ->order([$LorR => $DorA])
  383. ->first();
  384. if (empty($edge->{$LorR})) {
  385. return 0;
  386. }
  387. return $edge->{$LorR};
  388. }
  389. protected function _sync($shift, $dir = '+', $conditions = null, $field = 'both') {
  390. extract($this->config());
  391. if ($field === 'both') {
  392. $this->_sync($shift, $dir, $conditions, $left);
  393. $field = $right;
  394. }
  395. // updateAll + scope
  396. $exp = new QueryExpression();
  397. $exp->add("{$field} = ({$field} {$dir} {$shift})");
  398. $query = $this->_scope($this->_table->query());
  399. $query->update()
  400. ->set($exp);
  401. if ($conditions) {
  402. $conditions = "{$field} {$conditions}";
  403. $query->where($conditions);
  404. }
  405. $statement = $query->execute();
  406. $success = $statement->rowCount() > 0;
  407. return $success;
  408. }
  409. protected function _scope($query) {
  410. $config = $this->config();
  411. if (empty($config['scope'])) {
  412. return $query;
  413. } elseif (is_array($config['scope'])) {
  414. return $query->where($config['scope']);
  415. } elseif (is_callable($config['scope'])) {
  416. return $config['scope']($query);
  417. }
  418. return $query;
  419. }
  420. }