TreeBehavior.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  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. /**
  21. * Makes the table to which this is attached to behave like a nested set and
  22. * provides methods for managing and retrieving information out of the derived
  23. * hierarchical structure.
  24. *
  25. * Tables attaching this behavior are required to have a column referencing the
  26. * parent row, and two other numeric columns (lft and rght) where the implicit
  27. * order will be cached.
  28. *
  29. * For more information on what is a nested set and a how it works refer to
  30. * http://www.sitepoint.com/hierarchical-data-database-2/
  31. */
  32. class TreeBehavior extends Behavior {
  33. /**
  34. * Table instance
  35. *
  36. * @var \Cake\ORM\Table
  37. */
  38. protected $_table;
  39. /**
  40. * Default config
  41. *
  42. * These are merged with user-provided configuration when the behavior is used.
  43. *
  44. * @var array
  45. */
  46. protected $_defaultConfig = [
  47. 'implementedFinders' => [
  48. 'path' => 'findPath',
  49. 'children' => 'findChildren',
  50. 'treeList' => 'findTreeList'
  51. ],
  52. 'implementedMethods' => [
  53. 'childCount' => 'childCount',
  54. 'moveUp' => 'moveUp',
  55. 'moveDown' => 'moveDown',
  56. 'recover' => 'recover',
  57. 'removeFromTree' => 'removeFromTree'
  58. ],
  59. 'parent' => 'parent_id',
  60. 'left' => 'lft',
  61. 'right' => 'rght',
  62. 'scope' => null
  63. ];
  64. /**
  65. * Constructor
  66. *
  67. * @param Table $table The table this behavior is attached to.
  68. * @param array $config The config for this behavior.
  69. */
  70. public function __construct(Table $table, array $config = []) {
  71. parent::__construct($table, $config);
  72. $this->_table = $table;
  73. }
  74. /**
  75. * Before save listener.
  76. * Transparently manages setting the lft and rght fields if the parent field is
  77. * included in the parameters to be saved.
  78. *
  79. * @param \Cake\Event\Event the beforeSave event that was fired
  80. * @param \Cake\ORM\Entity the entity that is going to be saved
  81. * @return void
  82. * @throws \RuntimeException if the parent to set for the node is invalid
  83. */
  84. public function beforeSave(Event $event, Entity $entity) {
  85. $isNew = $entity->isNew();
  86. $config = $this->config();
  87. $parent = $entity->get($config['parent']);
  88. $primaryKey = (array)$this->_table->primaryKey();
  89. $dirty = $entity->dirty($config['parent']);
  90. if ($isNew && $parent) {
  91. if ($entity->get($primaryKey[0]) == $parent) {
  92. throw new \RuntimeException("Cannot set a node's parent as itself");
  93. }
  94. $parentNode = $this->_getNode($parent);
  95. $edge = $parentNode->get($config['right']);
  96. $entity->set($config['left'], $edge);
  97. $entity->set($config['right'], $edge + 1);
  98. $this->_sync(2, '+', ">= {$edge}");
  99. }
  100. if ($isNew && !$parent) {
  101. $edge = $this->_getMax();
  102. $entity->set($config['left'], $edge + 1);
  103. $entity->set($config['right'], $edge + 2);
  104. }
  105. if (!$isNew && $dirty && $parent) {
  106. $this->_setParent($entity, $parent);
  107. }
  108. if (!$isNew && $dirty && !$parent) {
  109. $this->_setAsRoot($entity);
  110. }
  111. }
  112. /**
  113. * Also deletes the nodes in the subtree of the entity to be delete
  114. *
  115. * @param \Cake\Event\Event the beforeDelete event that was fired
  116. * @param \Cake\ORM\Entity the entity that is going to be saved
  117. * @return void
  118. */
  119. public function beforeDelete(Event $event, Entity $entity) {
  120. $config = $this->config();
  121. $this->_ensureFields($entity);
  122. $left = $entity->get($config['left']);
  123. $right = $entity->get($config['right']);
  124. $diff = $right - $left + 1;
  125. if ($diff > 2) {
  126. $this->_table->deleteAll([
  127. "{$config['left']} >=" => $left + 1,
  128. "{$config['left']} <=" => $right - 1
  129. ]);
  130. }
  131. $this->_sync($diff, '-', "> {$right}");
  132. }
  133. /**
  134. * Sets the correct left and right values for the passed entity so it can be
  135. * updated to a new parent. It also makes the hole in the tree so the node
  136. * move can be done without corrupting the structure.
  137. *
  138. * @param \Cake\ORM\Entity $entity The entity to re-parent
  139. * @param mixed $parent the id of the parent to set
  140. * @return void
  141. * @throws \RuntimeException if the parent to set to the entity is not valid
  142. */
  143. protected function _setParent($entity, $parent) {
  144. $config = $this->config();
  145. $parentNode = $this->_getNode($parent);
  146. $this->_ensureFields($entity);
  147. $parentLeft = $parentNode->get($config['left']);
  148. $parentRight = $parentNode->get($config['right']);
  149. $right = $entity->get($config['right']);
  150. $left = $entity->get($config['left']);
  151. if ($parentLeft > $left && $parentLeft < $right) {
  152. throw new \RuntimeException(sprintf(
  153. 'Cannot use node "%s" as parent for entity "%s"',
  154. $parent,
  155. $entity->get($this->_table->primaryKey())
  156. ));
  157. }
  158. // Values for moving to the left
  159. $diff = $right - $left + 1;
  160. $targetLeft = $parentRight;
  161. $targetRight = $diff + $parentRight - 1;
  162. $min = $parentRight;
  163. $max = $left - 1;
  164. if ($left < $targetLeft) {
  165. //Moving to the right
  166. $targetLeft = $parentRight - $diff;
  167. $targetRight = $parentRight - 1;
  168. $min = $right + 1;
  169. $max = $parentRight - 1;
  170. $diff *= -1;
  171. }
  172. if ($right - $left > 1) {
  173. //Correcting internal subtree
  174. $internalLeft = $left + 1;
  175. $internalRight = $right - 1;
  176. $this->_sync($targetLeft - $left, '+', "BETWEEN {$internalLeft} AND {$internalRight}", true);
  177. }
  178. $this->_sync($diff, '+', "BETWEEN {$min} AND {$max}");
  179. if ($right - $left > 1) {
  180. $this->_unmarkInternalTree();
  181. }
  182. //Allocating new position
  183. $entity->set($config['left'], $targetLeft);
  184. $entity->set($config['right'], $targetRight);
  185. }
  186. /**
  187. * Updates the left and right column for the passed entity so it can be set as
  188. * a new root in the tree. It also modifies the ordering in the rest of the tree
  189. * so the structure remains valid
  190. *
  191. * @param \Cake\ORM\Entity $entity The entity to set as a new root
  192. * @return void
  193. */
  194. protected function _setAsRoot($entity) {
  195. $config = $this->config();
  196. $edge = $this->_getMax();
  197. $this->_ensureFields($entity);
  198. $right = $entity->get($config['right']);
  199. $left = $entity->get($config['left']);
  200. $diff = $right - $left;
  201. if ($right - $left > 1) {
  202. //Correcting internal subtree
  203. $internalLeft = $left + 1;
  204. $internalRight = $right - 1;
  205. $this->_sync($edge - $diff - $left, '+', "BETWEEN {$internalLeft} AND {$internalRight}", true);
  206. }
  207. $this->_sync($diff + 1, '-', "BETWEEN {$right} AND {$edge}");
  208. if ($right - $left > 1) {
  209. $this->_unmarkInternalTree();
  210. }
  211. $entity->set($config['left'], $edge - $diff);
  212. $entity->set($config['right'], $edge);
  213. }
  214. /**
  215. * Helper method used to invert the sign of the left and right columns that are
  216. * less than 0. They were set to negative values before so their absolute value
  217. * wouldn't change while performing other tree transformations.
  218. *
  219. * @return void
  220. */
  221. protected function _unmarkInternalTree() {
  222. $config = $this->config();
  223. $query = $this->_table->query();
  224. $this->_table->updateAll([
  225. $query->newExpr()->add("{$config['left']} = {$config['left']} * -1"),
  226. $query->newExpr()->add("{$config['right']} = {$config['right']} * -1"),
  227. ], [$config['left'] . ' <' => 0]);
  228. }
  229. /**
  230. * Custom finder method which can be used to return the list of nodes from the root
  231. * to a specific node in the tree. This custom finder requires that the key 'for'
  232. * is passed in the options containing the id of the node to get its path for.
  233. *
  234. * @param \Cake\ORM\Query $query The constructed query to modify
  235. * @param array $options the list of options for the query
  236. * @return \Cake\ORM\Query
  237. * @throws \InvalidArgumentException If the 'for' key is missing in options
  238. */
  239. public function findPath($query, $options) {
  240. if (empty($options['for'])) {
  241. throw new \InvalidArgumentException("The 'for' key is required for find('path')");
  242. }
  243. $config = $this->config();
  244. list($left, $right) = [$config['left'], $config['right']];
  245. $node = $this->_table->get($options['for'], ['fields' => [$left, $right]]);
  246. return $this->_scope($query)
  247. ->where([
  248. "$left <=" => $node->get($left),
  249. "$right >=" => $node->get($right)
  250. ]);
  251. }
  252. /**
  253. * Get the number of children nodes.
  254. *
  255. * @param \Cake\ORM\Entity $node The entity to count children for
  256. * @param boolean $direct whether to count all nodes in the subtree or just
  257. * direct children
  258. * @return integer Number of children nodes.
  259. */
  260. public function childCount(Entity $node, $direct = false) {
  261. $config = $this->config();
  262. list($parent, $left, $right) = [$config['parent'], $config['left'], $config['right']];
  263. if ($direct) {
  264. return $this->_scope($this->_table->find())
  265. ->where([$parent => $node->get($this->_table->primaryKey())])
  266. ->count();
  267. }
  268. $this->_ensureFields($node);
  269. return ($node->{$right} - $node->{$left} - 1) / 2;
  270. }
  271. /**
  272. * Get the children nodes of the current model
  273. *
  274. * Available options are:
  275. *
  276. * - for: The id of the record to read.
  277. * - direct: Boolean, whether to return only the direct (true), or all (false) children,
  278. * defaults to false (all children).
  279. *
  280. * If the direct option is set to true, only the direct children are returned (based upon the parent_id field)
  281. *
  282. * @param \Cake\ORM\Query $query
  283. * @param array $options Array of options as described above
  284. * @return \Cake\ORM\Query
  285. * @throws \InvalidArgumentException When the 'for' key is not passed in $options
  286. */
  287. public function findChildren($query, $options) {
  288. $config = $this->config();
  289. $options += ['for' => null, 'direct' => false];
  290. list($parent, $left, $right) = [$config['parent'], $config['left'], $config['right']];
  291. list($for, $direct) = [$options['for'], $options['direct']];
  292. if (empty($for)) {
  293. throw new \InvalidArgumentException("The 'for' key is required for find('children')");
  294. }
  295. if ($query->clause('order') === null) {
  296. $query->order([$left => 'ASC']);
  297. }
  298. if ($direct) {
  299. return $this->_scope($query)->where([$parent => $for]);
  300. }
  301. $node = $this->_getNode($for);
  302. return $this->_scope($query)
  303. ->where([
  304. "{$right} <" => $node->{$right},
  305. "{$left} >" => $node->{$left}
  306. ]);
  307. }
  308. /**
  309. * Gets a representation of the elements in the tree as a flat list where the keys are
  310. * the primary key for the table and the values are the display field for the table.
  311. * Values are prefixed to visually indicate relative depth in the tree.
  312. *
  313. * Avaliable options are:
  314. *
  315. * - keyPath: A dot separated path to fetch the field to use for the array key, or a closure to
  316. * return the key out of the provided row.
  317. * - valuePath: A dot separated path to fetch the field to use for the array value, or a closure to
  318. * return the value out of the provided row.
  319. * - spacer: A string to be used as prefix for denoting the depth in the tree for each item
  320. *
  321. * @param \Cake\ORM\Query $query
  322. * @param array $options Array of options as described above
  323. * @return \Cake\ORM\Query
  324. */
  325. public function findTreeList($query, $options) {
  326. return $this->_scope($query)
  327. ->find('threaded', ['parentField' => $this->config()['parent']])
  328. ->formatResults(function($results) use ($options) {
  329. $options += [
  330. 'keyPath' => $this->_table->primaryKey(),
  331. 'valuePath' => $this->_table->displayField(),
  332. 'spacer' => '_'
  333. ];
  334. return $results
  335. ->listNested()
  336. ->printer($options['valuePath'], $options['keyPath'], $options['spacer']);
  337. });
  338. }
  339. /**
  340. * Removes the current node from the tree, by positioning it as a new root
  341. * and re-parents all children up one level.
  342. *
  343. * Note that the node will not be deleted just moved away from its current position
  344. * without moving its children with it.
  345. *
  346. * @param \Cake\ORM\Entity $node The node to remove from the tree
  347. * @return \Cake\ORM\Entity|false the node after being removed from the tree or
  348. * false on error
  349. */
  350. public function removeFromTree(Entity $node) {
  351. return $this->_table->connection()->transactional(function() use ($node) {
  352. $this->_ensureFields($node);
  353. return $this->_removeFromTree($node);
  354. });
  355. }
  356. /**
  357. * Helper function containing the actual code for removeFromTree
  358. *
  359. * @param \Cake\ORM\Entity $node The node to remove from the tree
  360. * @return \Cake\ORM\Entity|false the node after being removed from the tree or
  361. * false on error
  362. */
  363. protected function _removeFromTree($node) {
  364. $config = $this->config();
  365. $left = $node->get($config['left']);
  366. $right = $node->get($config['right']);
  367. $parent = $node->get($config['parent']);
  368. $node->set($config['parent'], null);
  369. if ($right - $left == 1) {
  370. return $this->_table->save($node);
  371. }
  372. $primary = $this->_table->primaryKey();
  373. $this->_table->updateAll(
  374. [$config['parent'] => $parent],
  375. [$config['parent'] => $node->get($primary)]
  376. );
  377. $this->_sync(1, '-', 'BETWEEN ' . ($left + 1) . ' AND ' . ($right - 1));
  378. $this->_sync(2, '-', "> {$right}");
  379. $edge = $this->_getMax();
  380. $node->set($config['left'], $edge + 1);
  381. $node->set($config['right'], $edge + 2);
  382. $fields = [$config['parent'], $config['left'], $config['right']];
  383. $this->_table->updateAll($node->extract($fields), [$primary => $node->get($primary)]);
  384. foreach ($fields as $field) {
  385. $node->dirty($field, false);
  386. }
  387. return $node;
  388. }
  389. /**
  390. * Reorders the node without changing its parent.
  391. *
  392. * If the node is the first child, or is a top level node with no previous node
  393. * this method will return false
  394. *
  395. * @param \Cake\ORM\Entity $node The node to move
  396. * @param integer|boolean $number How many places to move the node, or true to move to first position
  397. * @throws \Cake\ORM\Error\RecordNotFoundException When node was not found
  398. * @return \Cake\ORM\Entity|boolean $node The node after being moved or false on failure
  399. */
  400. public function moveUp(Entity $node, $number = 1) {
  401. return $this->_table->connection()->transactional(function() use ($node, $number) {
  402. $this->_ensureFields($node);
  403. return $this->_moveUp($node, $number);
  404. });
  405. }
  406. /**
  407. * Helper function used with the actual code for moveUp
  408. *
  409. * @param \Cake\ORM\Entity $node The node to move
  410. * @param integer|boolean $number How many places to move the node, or true to move to first position
  411. * @throws \Cake\ORM\Error\RecordNotFoundException When node was not found
  412. * @return \Cake\ORM\Entity|boolean $node The node after being moved or false on failure
  413. */
  414. protected function _moveUp($node, $number) {
  415. $config = $this->config();
  416. list($parent, $left, $right) = [$config['parent'], $config['left'], $config['right']];
  417. if (!$number) {
  418. return false;
  419. }
  420. $parentLeft = 0;
  421. if ($node->get($parent)) {
  422. $parentLeft = $this->_getNode($node->get($parent))->get($left);
  423. }
  424. $edge = $this->_getMax();
  425. while ($number-- > 0) {
  426. list($nodeLeft, $nodeRight) = array_values($node->extract([$left, $right]));
  427. if ($parentLeft && ($nodeLeft - 1 == $parentLeft)) {
  428. break;
  429. }
  430. $nextNode = $this->_scope($this->_table->find())
  431. ->select([$left, $right])
  432. ->where([$right => ($nodeLeft - 1)])
  433. ->first();
  434. if (!$nextNode) {
  435. break;
  436. }
  437. $this->_sync($edge - $nextNode->{$left} + 1, '+', "BETWEEN {$nextNode->{$left}} AND {$nextNode->{$right}}");
  438. $this->_sync($nodeLeft - $nextNode->{$left}, '-', "BETWEEN {$nodeLeft} AND {$nodeRight}");
  439. $this->_sync($edge - $nextNode->{$left} - ($nodeRight - $nodeLeft), '-', "> {$edge}");
  440. $newLeft = $nodeLeft;
  441. if ($nodeLeft >= $nextNode->{$left} || $nodeLeft <= $nextNode->{$right}) {
  442. $newLeft -= $edge - $nextNode->{$left} + 1;
  443. }
  444. $newLeft = $nodeLeft - ($nodeLeft - $nextNode->{$left});
  445. $node->set($left, $newLeft);
  446. $node->set($right, $newLeft + ($nodeRight - $nodeLeft));
  447. }
  448. $node->dirty($left, false);
  449. $node->dirty($right, false);
  450. return $node;
  451. }
  452. /**
  453. * Reorders the node without changing the parent.
  454. *
  455. * If the node is the last child, or is a top level node with no subsequent node
  456. * this method will return false
  457. *
  458. * @param \Cake\ORM\Entity $node The node to move
  459. * @param integer|boolean $number How many places to move the node or true to move to last position
  460. * @throws \Cake\ORM\Error\RecordNotFoundException When node was not found
  461. * @return \Cake\ORM\Entity|boolean the entity after being moved or false on failure
  462. */
  463. public function moveDown(Entity $node, $number = 1) {
  464. return $this->_table->connection()->transactional(function() use ($node, $number) {
  465. $this->_ensureFields($node);
  466. return $this->_moveDown($node, $number);
  467. });
  468. }
  469. /**
  470. * Helper function used with the actual code for moveDown
  471. *
  472. * @param \Cake\ORM\Entity $node The node to move
  473. * @param integer|boolean $number How many places to move the node, or true to move to last position
  474. * @throws \Cake\ORM\Error\RecordNotFoundException When node was not found
  475. * @return \Cake\ORM\Entity|boolean $node The node after being moved or false on failure
  476. */
  477. protected function _moveDown($node, $number) {
  478. $config = $this->config();
  479. list($parent, $left, $right) = [$config['parent'], $config['left'], $config['right']];
  480. if (!$number) {
  481. return false;
  482. }
  483. $parentRight = 0;
  484. if ($node->get($parent)) {
  485. $parentRight = $this->_getNode($node->get($parent))->get($right);
  486. }
  487. if ($number === true) {
  488. $number = PHP_INT_MAX;
  489. }
  490. $edge = $this->_getMax();
  491. while ($number-- > 0) {
  492. list($nodeLeft, $nodeRight) = array_values($node->extract([$left, $right]));
  493. if ($parentRight && ($nodeRight + 1 == $parentRight)) {
  494. break;
  495. }
  496. $nextNode = $this->_scope($this->_table->find())
  497. ->select([$left, $right])
  498. ->where([$left => $nodeRight + 1])
  499. ->first();
  500. if (!$nextNode) {
  501. break;
  502. }
  503. $this->_sync($edge - $nodeLeft + 1, '+', "BETWEEN {$nodeLeft} AND {$nodeRight}");
  504. $this->_sync($nextNode->{$left} - $nodeLeft, '-', "BETWEEN {$nextNode->{$left}} AND {$nextNode->{$right}}");
  505. $this->_sync($edge - $nodeLeft - ($nextNode->{$right} - $nextNode->{$left}), '-', "> {$edge}");
  506. $newLeft = $edge + 1;
  507. if ($newLeft >= $nextNode->{$left} || $newLeft <= $nextNode->{$right}) {
  508. $newLeft -= $nextNode->{$left} - $nodeLeft;
  509. }
  510. $newLeft -= $nextNode->{$right} - $nextNode->{$left} - 1;
  511. $node->set($left, $newLeft);
  512. $node->set($right, $newLeft + ($nodeRight - $nodeLeft));
  513. }
  514. $node->dirty($left, false);
  515. $node->dirty($right, false);
  516. return $node;
  517. }
  518. /**
  519. * Returns a single node from the tree from its primary key
  520. *
  521. * @param mixed $id
  522. * @return Cake\ORM\Entity
  523. * @throws \Cake\ORM\Error\RecordNotFoundException When node was not found
  524. */
  525. protected function _getNode($id) {
  526. $config = $this->config();
  527. list($parent, $left, $right) = [$config['parent'], $config['left'], $config['right']];
  528. $primaryKey = $this->_table->primaryKey();
  529. $node = $this->_scope($this->_table->find())
  530. ->select([$parent, $left, $right])
  531. ->where([$primaryKey => $id])
  532. ->first();
  533. if (!$node) {
  534. throw new \Cake\ORM\Error\RecordNotFoundException("Node \"{$id}\" was not found in the tree.");
  535. }
  536. return $node;
  537. }
  538. /**
  539. * Recovers the lft and right column values out of the hirearchy defined by the
  540. * parent column.
  541. *
  542. * @return void
  543. */
  544. public function recover() {
  545. $this->_table->connection()->transactional(function() {
  546. $this->_recoverTree();
  547. });
  548. }
  549. /**
  550. * Recursive method used to recover a single level of the tree
  551. *
  552. * @param integer $counter The Last left column value that was assigned
  553. * @param mixed $parentId the parent id of the level to be recovered
  554. * @return integer Ne next value to use for the left column
  555. */
  556. protected function _recoverTree($counter = 0, $parentId = null) {
  557. $config = $this->config();
  558. list($parent, $left, $right) = [$config['parent'], $config['left'], $config['right']];
  559. $pk = (array)$this->_table->primaryKey();
  560. $query = $this->_scope($this->_table->query())
  561. ->select($pk)
  562. ->where(function($exp) use ($parentId, $parent) {
  563. return $parentId === null ? $exp->isNull($parent) : $exp->eq($parent, $parentId);
  564. })
  565. ->order($pk)
  566. ->hydrate(false)
  567. ->bufferResults(false);
  568. $leftCounter = $counter;
  569. foreach ($query as $row) {
  570. $counter++;
  571. $counter = $this->_recoverTree($counter, $row[$pk[0]]);
  572. }
  573. if ($parentId === null) {
  574. return $counter;
  575. }
  576. $this->_table->updateAll(
  577. [$left => $leftCounter, $right => $counter + 1],
  578. [$pk[0] => $parentId]
  579. );
  580. return $counter + 1;
  581. }
  582. /**
  583. * Returns the maximum index value in the table.
  584. *
  585. * @return integer
  586. */
  587. protected function _getMax() {
  588. $config = $this->config();
  589. $field = $config['right'];
  590. $edge = $this->_scope($this->_table->find())
  591. ->select([$field])
  592. ->order([$field => 'DESC'])
  593. ->first();
  594. if (empty($edge->{$field})) {
  595. return 0;
  596. }
  597. return $edge->{$field};
  598. }
  599. /**
  600. * Auxiliary function used to automatically alter the value of both the left and
  601. * right columns by a certain amount that match the passed conditions
  602. *
  603. * @param integer $shift the value to use for operating the left and right columns
  604. * @param string $dir The operator to use for shifting the value (+/-)
  605. * @param string $conditions a SQL snipped to be used for comparing left or right
  606. * against it.
  607. * @param boolean $mark whether to mark the updated values so that they can not be
  608. * modified by future calls to this function.
  609. * @return void
  610. */
  611. protected function _sync($shift, $dir, $conditions, $mark = false) {
  612. $config = $this->config();
  613. foreach ([$config['left'], $config['right']] as $field) {
  614. $query = $this->_scope($this->_table->query());
  615. $mark = $mark ? '*-1' : '';
  616. $template = sprintf('%s = (%s %s %s)%s', $field, $field, $dir, $shift, $mark);
  617. $query->update()->set($query->newExpr()->add($template));
  618. $query->where("{$field} {$conditions}");
  619. $query->execute();
  620. }
  621. }
  622. /**
  623. * Alters the passed query so that it only returns scoped records as defined
  624. * in the tree configuration.
  625. *
  626. * @param \Cake\ORM\Query $query the Query to modify
  627. * @return \Cake\ORM\Query
  628. */
  629. protected function _scope($query) {
  630. $config = $this->config();
  631. if (is_array($config['scope'])) {
  632. return $query->where($config['scope']);
  633. } elseif (is_callable($config['scope'])) {
  634. return $config['scope']($query);
  635. }
  636. return $query;
  637. }
  638. /**
  639. * Ensures that the provided entity contains non-empty values for the left and
  640. * right fields
  641. *
  642. * @param \Cake\ORM\Entity $entity The entity to ensure fields for
  643. * @return void
  644. */
  645. protected function _ensureFields($entity) {
  646. $config = $this->config();
  647. $fields = [$config['left'], $config['right']];
  648. $values = array_filter($entity->extract($fields));
  649. if (count($values) === count($fields)) {
  650. return;
  651. }
  652. $fresh = $this->_table->get($entity->get($this->_table->primaryKey()), $fields);
  653. $entity->set($fresh->extract($fields), ['guard' => false]);
  654. foreach ($fields as $field) {
  655. $entity->dirty($field, false);
  656. }
  657. }
  658. }