TreeBehavior.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  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 Cake\Event\Event;
  17. use Cake\ORM\Behavior;
  18. use Cake\ORM\Entity;
  19. use Cake\ORM\Table;
  20. class TreeBehavior extends Behavior {
  21. /**
  22. * Table instance
  23. *
  24. * @var \Cake\ORM\Table
  25. */
  26. protected $_table;
  27. /**
  28. * Default config
  29. *
  30. * These are merged with user-provided configuration when the behavior is used.
  31. *
  32. * @var array
  33. */
  34. protected $_defaultConfig = [
  35. 'implementedFinders' => [
  36. 'path' => 'findPath',
  37. 'children' => 'findChildren',
  38. ],
  39. 'implementedMethods' => [
  40. 'childCount' => 'childCount',
  41. 'moveUp' => 'moveUp',
  42. 'moveDown' => 'moveDown',
  43. 'recover' => 'recover',
  44. 'removeFromTree' => 'removeFromTree'
  45. ],
  46. 'parent' => 'parent_id',
  47. 'left' => 'lft',
  48. 'right' => 'rght',
  49. 'scope' => null
  50. ];
  51. /**
  52. * Constructor
  53. *
  54. * @param Table $table The table this behavior is attached to.
  55. * @param array $config The config for this behavior.
  56. */
  57. public function __construct(Table $table, array $config = []) {
  58. parent::__construct($table, $config);
  59. $this->_table = $table;
  60. }
  61. /**
  62. * Before save listener.
  63. * Transparently manages setting the lft and rght fields if the parent field is
  64. * included in the parameters to be saved.
  65. *
  66. * @param \Cake\Event\Event the beforeSave event that was fired
  67. * @param \Cake\ORM\Entity the entity that is going to be saved
  68. * @return void
  69. * @throws \RuntimeException if the parent to set for the node is invalid
  70. */
  71. public function beforeSave(Event $event, Entity $entity) {
  72. $isNew = $entity->isNew();
  73. $config = $this->config();
  74. $parent = $entity->get($config['parent']);
  75. $primaryKey = (array)$this->_table->primaryKey();
  76. $dirty = $entity->dirty($config['parent']);
  77. if ($isNew && $parent) {
  78. if ($entity->get($primaryKey[0]) == $parent) {
  79. throw new \RuntimeException("Cannot set a node's parent as itself");
  80. }
  81. $parentNode = $this->_getNode($parent);
  82. $edge = $parentNode->get($config['right']);
  83. $entity->set($config['left'], $edge);
  84. $entity->set($config['right'], $edge + 1);
  85. $this->_sync(2, '+', ">= {$edge}");
  86. }
  87. if ($isNew && !$parent) {
  88. $edge = $this->_getMax();
  89. $entity->set($config['left'], $edge + 1);
  90. $entity->set($config['right'], $edge + 2);
  91. }
  92. if (!$isNew && $dirty && $parent) {
  93. $this->_setParent($entity, $parent);
  94. }
  95. if (!$isNew && $dirty && !$parent) {
  96. $this->_setAsRoot($entity);
  97. }
  98. }
  99. /**
  100. * Also deletes the nodes in the subtree of the entity to be delete
  101. *
  102. * @param \Cake\Event\Event the beforeDelete event that was fired
  103. * @param \Cake\ORM\Entity the entity that is going to be saved
  104. * @return void
  105. */
  106. public function beforeDelete(Event $event, Entity $entity) {
  107. $config = $this->config();
  108. $left = $entity->get($config['left']);
  109. $right = $entity->get($config['right']);
  110. $diff = $right - $left + 1;
  111. if ($diff > 2) {
  112. $this->_table->deleteAll([
  113. "{$config['left']} >=" => $left + 1,
  114. "{$config['left']} <=" => $right - 1
  115. ]);
  116. }
  117. $this->_sync($diff, '-', "> {$right}");
  118. }
  119. /**
  120. * Sets the correct left and right values for the passed entity so it can be
  121. * updated to a new parent. It also makes the hole in the tree so the node
  122. * move can be done without corrupting the structure.
  123. *
  124. * @param \Cake\ORM\Entity $entity The entity to re-parent
  125. * @param mixed $parent the id of the parent to set
  126. * @return void
  127. * @throws \RuntimeException if the parent to set to the entity is not valid
  128. */
  129. protected function _setParent($entity, $parent) {
  130. $config = $this->config();
  131. $parentNode = $this->_getNode($parent);
  132. $parentLeft = $parentNode->get($config['left']);
  133. $parentRight = $parentNode->get($config['right']);
  134. $right = $entity->get($config['right']);
  135. $left = $entity->get($config['left']);
  136. if ($parentLeft > $left && $parentLeft < $right) {
  137. throw new \RuntimeException(sprintf(
  138. 'Cannot use node "%s" as parent for entity "%s"',
  139. $parent,
  140. $entity->get($this->_table->primaryKey())
  141. ));
  142. }
  143. // Values for moving to the left
  144. $diff = $right - $left + 1;
  145. $targetLeft = $parentRight;
  146. $targetRight = $diff + $parentRight - 1;
  147. $min = $parentRight;
  148. $max = $left - 1;
  149. if ($left < $targetLeft) {
  150. //Moving to the right
  151. $targetLeft = $parentRight - $diff;
  152. $targetRight = $parentRight - 1;
  153. $min = $right + 1;
  154. $max = $parentRight - 1;
  155. $diff *= -1;
  156. }
  157. if ($right - $left > 1) {
  158. //Correcting internal subtree
  159. $internalLeft = $left + 1;
  160. $internalRight = $right - 1;
  161. $this->_sync($targetLeft - $left, '+', "BETWEEN {$internalLeft} AND {$internalRight}", true);
  162. }
  163. $this->_sync($diff, '+', "BETWEEN {$min} AND {$max}");
  164. if ($right - $left > 1) {
  165. $this->_unmarkInternalTree();
  166. }
  167. //Allocating new position
  168. $entity->set($config['left'], $targetLeft);
  169. $entity->set($config['right'], $targetRight);
  170. }
  171. /**
  172. * Updates the left and right column for the passed entity so it can be set as
  173. * a new root in the tree. It also modifies the ordering in the rest of the tree
  174. * so the structure remains valid
  175. *
  176. * @param \Cake\ORM\Entity $entity The entity to set as a new root
  177. * @return void
  178. */
  179. protected function _setAsRoot($entity) {
  180. $config = $this->config();
  181. $edge = $this->_getMax();
  182. $right = $entity->get($config['right']);
  183. $left = $entity->get($config['left']);
  184. $diff = $right - $left;
  185. if ($right - $left > 1) {
  186. //Correcting internal subtree
  187. $internalLeft = $left + 1;
  188. $internalRight = $right - 1;
  189. $this->_sync($edge - $diff - $left, '+', "BETWEEN {$internalLeft} AND {$internalRight}", true);
  190. }
  191. $this->_sync($diff + 1, '-', "BETWEEN {$right} AND {$edge}");
  192. if ($right - $left > 1) {
  193. $this->_unmarkInternalTree();
  194. }
  195. $entity->set($config['left'], $edge - $diff);
  196. $entity->set($config['right'], $edge);
  197. }
  198. /**
  199. * Helper method used to invert the sign of the left and right columns that are
  200. * less than 0. They were set to negative values before so their absolute value
  201. * wouldn't change while performing other tree transformations.
  202. *
  203. * @return void
  204. */
  205. protected function _unmarkInternalTree() {
  206. $config = $this->config();
  207. $query = $this->_table->query();
  208. $this->_table->updateAll([
  209. $query->newExpr()->add("{$config['left']} = {$config['left']} * -1"),
  210. $query->newExpr()->add("{$config['right']} = {$config['right']} * -1"),
  211. ], [$config['left'] . ' <' => 0]);
  212. }
  213. /**
  214. * Custom finder method which can be used to return the list of nodes from the root
  215. * to a specific node in the tree. This custom finder requires that the key 'for'
  216. * is passed in the options containing the id of the node to get its path for.
  217. *
  218. * @param \Cake\ORM\Query $query The constructed query to modify
  219. * @param array $options the list of options for the query
  220. * @return \Cake\ORM\Query
  221. * @throws \InvalidArgumentException If the 'for' key is missing in options
  222. */
  223. public function findPath($query, $options) {
  224. if (empty($options['for'])) {
  225. throw new \InvalidArgumentException("The 'for' key is required for find('path')");
  226. }
  227. $config = $this->config();
  228. list($left, $right) = [$config['left'], $config['right']];
  229. $node = $this->_table->get($options['for'], ['fields' => [$left, $right]]);
  230. return $this->_scope($query)
  231. ->where([
  232. "$left <=" => $node->get($left),
  233. "$right >=" => $node->get($right)
  234. ]);
  235. }
  236. /**
  237. * Get the number of children nodes.
  238. *
  239. * @param integer|string $id The id of the record to read
  240. * @param boolean $direct whether to count all nodes in the subtree or just
  241. * direct children
  242. * @return integer Number of children nodes.
  243. */
  244. public function childCount($id, $direct = false) {
  245. $config = $this->config();
  246. list($parent, $left, $right) = [$config['parent'], $config['left'], $config['right']];
  247. if ($direct) {
  248. return $this->_scope($this->_table->find())
  249. ->where([$parent => $id])
  250. ->count();
  251. }
  252. $node = $this->_getNode($id);
  253. return ($node->{$right} - $node->{$left} - 1) / 2;
  254. }
  255. /**
  256. * Get the children nodes of the current model
  257. *
  258. * Available options are:
  259. *
  260. * - for: The id of the record to read.
  261. * - direct: Boolean, whether to return only the direct (true), or all (false) children,
  262. * defaults to false (all children).
  263. *
  264. * If the direct option is set to true, only the direct children are returned (based upon the parent_id field)
  265. *
  266. * @param array $options Array of options as described above
  267. * @return \Cake\ORM\Query
  268. * @throws \Cake\ORM\Error\RecordNotFoundException When node was not found
  269. * @throws \InvalidArgumentException When the 'for' key is not passed in $options
  270. */
  271. public function findChildren($query, $options) {
  272. $config = $this->config();
  273. $options += ['for' => null, 'direct' => false];
  274. list($parent, $left, $right) = [$config['parent'], $config['left'], $config['right']];
  275. list($for, $direct) = [$options['for'], $options['direct']];
  276. if (empty($for)) {
  277. throw new \InvalidArgumentException("The 'for' key is required for find('children')");
  278. }
  279. if ($query->clause('order') === null) {
  280. $query->order([$left => 'ASC']);
  281. }
  282. if ($direct) {
  283. return $this->_scope($query)->where([$parent => $for]);
  284. }
  285. $node = $this->_getNode($for);
  286. return $this->_scope($query)
  287. ->where([
  288. "{$right} <" => $node->{$right},
  289. "{$left} >" => $node->{$left}
  290. ]);
  291. }
  292. public function removeFromTree($node) {
  293. $config = $this->config();
  294. $left = $node->get($config['left']);
  295. $right = $node->get($config['right']);
  296. $parent = $node->get($config['parent']);
  297. if ($right - $left > 1) {
  298. $this->_table->updateAll(
  299. [$config['parent'] => $parent],
  300. [$config['parent'] => $id]
  301. );
  302. $this->_sync(1, '-', 'BETWEEN ' . ($left + 1) . ' AND ' . ($right - 1));
  303. $this->_sync(2, '-', "> {$right}");
  304. }
  305. $node->set($config['parent'], null);
  306. return $this->_table->save($node);
  307. }
  308. /**
  309. * Reorders the node without changing its parent.
  310. *
  311. * If the node is the first child, or is a top level node with no previous node
  312. * this method will return false
  313. *
  314. * @param integer|string $id The id of the record to move
  315. * @param integer|boolean $number How many places to move the node, or true to move to first position
  316. * @throws \Cake\ORM\Error\RecordNotFoundException When node was not found
  317. * @return boolean true on success, false on failure
  318. */
  319. public function moveUp($id, $number = 1) {
  320. $config = $this->config();
  321. list($parent, $left, $right) = [$config['parent'], $config['left'], $config['right']];
  322. if (!$number) {
  323. return false;
  324. }
  325. $node = $this->_getNode($id);
  326. if ($node->{$parent}) {
  327. $parentNode = $this->_table->get($node->{$parent}, ['fields' => [$left, $right]]);
  328. if (($node->{$left} - 1) == $parentNode->{$left}) {
  329. return false;
  330. }
  331. }
  332. $previousNode = $this->_scope($this->_table->find())
  333. ->select([$left, $right])
  334. ->where([$right => ($node->{$left} - 1)])
  335. ->first();
  336. if (!$previousNode) {
  337. return false;
  338. }
  339. $edge = $this->_getMax();
  340. $this->_sync($edge - $previousNode->{$left} + 1, '+', "BETWEEN {$previousNode->{$left}} AND {$previousNode->{$right}}");
  341. $this->_sync($node->{$left} - $previousNode->{$left}, '-', "BETWEEN {$node->{$left}} AND {$node->{$right}}");
  342. $this->_sync($edge - $previousNode->{$left} - ($node->{$right} - $node->{$left}), '-', "> {$edge}");
  343. if (is_int($number)) {
  344. $number--;
  345. }
  346. if ($number) {
  347. $this->moveUp($id, $number);
  348. }
  349. return true;
  350. }
  351. /**
  352. * Reorders the node without changing the parent.
  353. *
  354. * If the node is the last child, or is a top level node with no subsequent node
  355. * this method will return false
  356. *
  357. * @param integer|string $id The id of the record to move
  358. * @param integer|boolean $number How many places to move the node or true to move to last position
  359. * @throws \Cake\ORM\Error\RecordNotFoundException When node was not found
  360. * @return boolean true on success, false on failure
  361. */
  362. public function moveDown($id, $number = 1) {
  363. $config = $this->config();
  364. list($parent, $left, $right) = [$config['parent'], $config['left'], $config['right']];
  365. if (!$number) {
  366. return false;
  367. }
  368. $node = $this->_getNode($id);
  369. if ($node->{$parent}) {
  370. $parentNode = $this->_table->get($node->{$parent}, ['fields' => [$left, $right]]);
  371. if (($node->{$right} + 1) == $parentNode->{$right}) {
  372. return false;
  373. }
  374. }
  375. $nextNode = $this->_scope($this->_table->find())
  376. ->select([$left, $right])
  377. ->where([$left => $node->{$right} + 1])
  378. ->first();
  379. if (!$nextNode) {
  380. return false;
  381. }
  382. $edge = $this->_getMax();
  383. $this->_sync($edge - $node->{$left} + 1, '+', "BETWEEN {$node->{$left}} AND {$node->{$right}}");
  384. $this->_sync($nextNode->{$left} - $node->{$left}, '-', "BETWEEN {$nextNode->{$left}} AND {$nextNode->{$right}}");
  385. $this->_sync($edge - $node->{$left} - ($nextNode->{$right} - $nextNode->{$left}), '-', "> {$edge}");
  386. if (is_int($number)) {
  387. $number--;
  388. }
  389. if ($number) {
  390. $this->moveDown($id, $number);
  391. }
  392. return true;
  393. }
  394. /**
  395. * Returns a single node from the tree from its primary key
  396. *
  397. * @param mixed $id
  398. * @return Cake\ORM\Entity
  399. */
  400. protected function _getNode($id) {
  401. $config = $this->config();
  402. list($parent, $left, $right) = [$config['parent'], $config['left'], $config['right']];
  403. $primaryKey = $this->_table->primaryKey();
  404. $node = $this->_scope($this->_table->find())
  405. ->select([$parent, $left, $right])
  406. ->where([$primaryKey => $id])
  407. ->first();
  408. if (!$node) {
  409. throw new \Cake\ORM\Error\RecordNotFoundException("Node \"{$id}\" was not found in the tree.");
  410. }
  411. return $node;
  412. }
  413. /**
  414. * Recovers the lft and right column values out of the hirearchy defined by the
  415. * parent column.
  416. *
  417. * @return void
  418. */
  419. public function recover() {
  420. $this->_table->connection()->transactional(function() {
  421. $this->_recoverTree();
  422. });
  423. }
  424. /**
  425. * Recursive method used to recover a single level of the tree
  426. *
  427. * @param integer $counter The Last left column value that was assigned
  428. * @param mixed $parentId the parent id of the level to be recovered
  429. * @return integer Ne next value to use for the left column
  430. */
  431. protected function _recoverTree($counter = 0, $parentId = null) {
  432. $config = $this->config();
  433. list($parent, $left, $right) = [$config['parent'], $config['left'], $config['right']];
  434. $pk = (array)$this->_table->primaryKey();
  435. $query = $this->_scope($this->_table->query())
  436. ->select($pk)
  437. ->where(function($exp) use ($parentId, $parent) {
  438. return $parentId === null ? $exp->isNull($parent) : $exp->eq($parent, $parentId);
  439. })
  440. ->order($pk)
  441. ->hydrate(false)
  442. ->bufferResults(false);
  443. $leftCounter = $counter;
  444. foreach ($query as $row) {
  445. $counter++;
  446. $counter = $this->_recoverTree($counter, $row[$pk[0]]);
  447. }
  448. if ($parentId === null) {
  449. return $counter;
  450. }
  451. $this->_table->updateAll(
  452. [$left => $leftCounter, $right => $counter + 1],
  453. [$pk[0] => $parentId]
  454. );
  455. return $counter + 1;
  456. }
  457. /**
  458. * Returns the maximum index value in the table.
  459. *
  460. * @return integer
  461. */
  462. protected function _getMax() {
  463. return $this->_getMaxOrMin('max');
  464. }
  465. /**
  466. * Returns the minimum index value in the table.
  467. *
  468. * @return integer
  469. */
  470. protected function _getMin() {
  471. return $this->_getMaxOrMin('min');
  472. }
  473. /**
  474. * Get the maximum|minimum index value in the table.
  475. *
  476. * @param string $maxOrMin Either 'max' or 'min'
  477. * @return integer
  478. */
  479. protected function _getMaxOrMin($maxOrMin = 'max') {
  480. $config = $this->config();
  481. $field = $maxOrMin === 'max' ? $config['right'] : $config['left'];
  482. $direction = $maxOrMin === 'max' ? 'DESC' : 'ASC';
  483. $edge = $this->_scope($this->_table->find())
  484. ->select([$field])
  485. ->order([$field => $direction])
  486. ->first();
  487. if (empty($edge->{$field})) {
  488. return 0;
  489. }
  490. return $edge->{$field};
  491. }
  492. /**
  493. * Auxiliary function used to automatically alter the value of both the left and
  494. * right columns by a certain amount that match the passed conditions
  495. *
  496. * @param integer $shift the value to use for operating the left and right columns
  497. * @param string $dir The operator to use for shifting the value (+/-)
  498. * @param string $conditions a SQL snipped to be used for comparing left or right
  499. * against it.
  500. * @param boolean $mark whether to mark the updated values so that they can not be
  501. * modified by future calls to this function.
  502. * @return void
  503. */
  504. protected function _sync($shift, $dir, $conditions, $mark = false) {
  505. $config = $this->config();
  506. foreach ([$config['left'], $config['right']] as $field) {
  507. $query = $this->_scope($this->_table->query());
  508. $mark = $mark ? '*-1' : '';
  509. $template = sprintf('%s = (%s %s %s)%s', $field, $field, $dir, $shift, $mark);
  510. $query->update()->set($query->newExpr()->add($template));
  511. $query->where("{$field} {$conditions}");
  512. $query->execute();
  513. }
  514. }
  515. /**
  516. * Alters the passed query so that it only returns scoped records as defined
  517. * in the tree configuration.
  518. *
  519. * @param \Cake\ORM\Query $query the Query to modify
  520. * @return \Cake\ORM\Query
  521. */
  522. protected function _scope($query) {
  523. $config = $this->config();
  524. if (is_array($config['scope'])) {
  525. return $query->where($config['scope']);
  526. } elseif (is_callable($config['scope'])) {
  527. return $config['scope']($query);
  528. }
  529. return $query;
  530. }
  531. }