TreeBehavior.php 15 KB

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