TreeBehavior.php 18 KB

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