NestedTreeRepository.php 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  1. <?php
  2. namespace Gedmo\Tree\Entity\Repository;
  3. use Gedmo\Tool\Wrapper\EntityWrapper;
  4. use Doctrine\ORM\Query,
  5. Gedmo\Tree\Strategy,
  6. Gedmo\Tree\Strategy\ORM\Nested,
  7. Gedmo\Exception\InvalidArgumentException,
  8. Doctrine\ORM\Proxy\Proxy;
  9. /**
  10. * The NestedTreeRepository has some useful functions
  11. * to interact with NestedSet tree. Repository uses
  12. * the strategy used by listener
  13. *
  14. * @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
  15. * @package Gedmo.Tree.Entity.Repository
  16. * @subpackage NestedTreeRepository
  17. * @link http://www.gediminasm.org
  18. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  19. */
  20. class NestedTreeRepository extends AbstractTreeRepository
  21. {
  22. /**
  23. * Get all root nodes query
  24. *
  25. * @return Query
  26. */
  27. public function getRootNodesQuery()
  28. {
  29. $meta = $this->getClassMetadata();
  30. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  31. $qb = $this->_em->createQueryBuilder();
  32. $qb->select('node')
  33. ->from($config['useObjectClass'], 'node')
  34. ->where('node.' . $config['parent'] . " IS NULL")
  35. ->orderBy('node.' . $config['left'], 'ASC');
  36. return $qb->getQuery();
  37. }
  38. /**
  39. * Get all root nodes
  40. *
  41. * @return array
  42. */
  43. public function getRootNodes()
  44. {
  45. return $this->getRootNodesQuery()->getResult();
  46. }
  47. /**
  48. * Allows the following 'virtual' methods:
  49. * - persistAsFirstChild($node)
  50. * - persistAsFirstChildOf($node, $parent)
  51. * - persistAsLastChild($node)
  52. * - persistAsLastChildOf($node, $parent)
  53. * - persistAsNextSibling($node)
  54. * - persistAsNextSiblingOf($node, $sibling)
  55. * - persistAsPrevSibling($node)
  56. * - persistAsPrevSiblingOf($node, $sibling)
  57. * Inherited virtual methods:
  58. * - find*
  59. *
  60. * @see \Doctrine\ORM\EntityRepository
  61. * @throws InvalidArgumentException - If arguments are invalid
  62. * @throws BadMethodCallException - If the method called is an invalid find* or persistAs* method
  63. * or no find* either persistAs* method at all and therefore an invalid method call.
  64. * @return mixed - TreeNestedRepository if persistAs* is called
  65. */
  66. public function __call($method, $args)
  67. {
  68. if (substr($method, 0, 9) === 'persistAs') {
  69. if (!isset($args[0])) {
  70. throw new \Gedmo\Exception\InvalidArgumentException('Node to persist must be available as first argument');
  71. }
  72. $node = $args[0];
  73. $wrapped = new EntityWrapper($node, $this->_em);
  74. $meta = $this->getClassMetadata();
  75. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  76. $position = substr($method, 9);
  77. if (substr($method, -2) === 'Of') {
  78. if (!isset($args[1])) {
  79. throw new \Gedmo\Exception\InvalidArgumentException('If "Of" is specified you must provide parent or sibling as the second argument');
  80. }
  81. $parent = $args[1];
  82. $wrapped->setPropertyValue($config['parent'], $parent);
  83. $position = substr($position, 0, -2);
  84. }
  85. $wrapped->setPropertyValue($config['left'], 0); // simulate changeset
  86. $oid = spl_object_hash($node);
  87. $this->listener
  88. ->getStrategy($this->_em, $meta->name)
  89. ->setNodePosition($oid, $position);
  90. $this->_em->persist($node);
  91. return $this;
  92. }
  93. return parent::__call($method, $args);
  94. }
  95. /**
  96. * Get the Tree path query by given $node
  97. *
  98. * @param object $node
  99. * @throws InvalidArgumentException - if input is not valid
  100. * @return Query
  101. */
  102. public function getPathQuery($node)
  103. {
  104. $meta = $this->getClassMetadata();
  105. if (!$node instanceof $meta->name) {
  106. throw new InvalidArgumentException("Node is not related to this repository");
  107. }
  108. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  109. $wrapped = new EntityWrapper($node, $this->_em);
  110. if (!$wrapped->hasValidIdentifier()) {
  111. throw new InvalidArgumentException("Node is not managed by UnitOfWork");
  112. }
  113. $left = $wrapped->getPropertyValue($config['left']);
  114. $right = $wrapped->getPropertyValue($config['right']);
  115. $qb = $this->_em->createQueryBuilder();
  116. $qb->select('node')
  117. ->from($config['useObjectClass'], 'node')
  118. ->where('node.' . $config['left'] . " <= :left")
  119. ->andWhere('node.' . $config['right'] . " >= :right")
  120. ->orderBy('node.' . $config['left'], 'ASC');
  121. if (isset($config['root'])) {
  122. $rootId = $wrapped->getPropertyValue($config['root']);
  123. $qb->andWhere("node.{$config['root']} = {$rootId}");
  124. }
  125. $q = $qb->getQuery();
  126. $q->setParameters(compact('left', 'right'));
  127. return $q;
  128. }
  129. /**
  130. * Get the Tree path of Nodes by given $node
  131. *
  132. * @param object $node
  133. * @return array - list of Nodes in path
  134. */
  135. public function getPath($node)
  136. {
  137. return $this->getPathQuery($node)->getResult();
  138. }
  139. /**
  140. * Counts the children of given TreeNode
  141. *
  142. * @param object $node - if null counts all records in tree
  143. * @param boolean $direct - true to count only direct children
  144. * @throws InvalidArgumentException - if input is not valid
  145. * @return integer
  146. */
  147. public function childCount($node = null, $direct = false)
  148. {
  149. $count = 0;
  150. $meta = $this->getClassMetadata();
  151. $nodeId = $meta->getSingleIdentifierFieldName();
  152. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  153. if (null !== $node) {
  154. if ($node instanceof $meta->name) {
  155. $wrapped = new EntityWrapper($node, $this->_em);
  156. if (!$wrapped->hasValidIdentifier()) {
  157. throw new InvalidArgumentException("Node is not managed by UnitOfWork");
  158. }
  159. if ($direct) {
  160. $id = $wrapped->getIdentifier();
  161. $qb = $this->_em->createQueryBuilder();
  162. $qb->select('COUNT(node.' . $nodeId . ')')
  163. ->from($config['useObjectClass'], 'node')
  164. ->where('node.' . $config['parent'] . ' = ' . $id);
  165. if (isset($config['root'])) {
  166. $rootId = $wrapped->getPropertyValue($config['root']);
  167. $qb->andWhere("node.{$config['root']} = {$rootId}");
  168. }
  169. $q = $qb->getQuery();
  170. $count = intval($q->getSingleScalarResult());
  171. } else {
  172. $left = $wrapped->getPropertyValue($config['left']);
  173. $right = $wrapped->getPropertyValue($config['right']);
  174. if ($left && $right) {
  175. $count = ($right - $left - 1) / 2;
  176. }
  177. }
  178. } else {
  179. throw new InvalidArgumentException("Node is not related to this repository");
  180. }
  181. } else {
  182. $dql = "SELECT COUNT(node.{$nodeId}) FROM " . $config['useObjectClass'] . " node";
  183. if ($direct) {
  184. $dql .= ' WHERE node.' . $config['parent'] . ' IS NULL';
  185. }
  186. $q = $this->_em->createQuery($dql);
  187. $count = intval($q->getSingleScalarResult());
  188. }
  189. return $count;
  190. }
  191. /**
  192. * Get tree children query followed by given $node
  193. *
  194. * @param object $node - if null, all tree nodes will be taken
  195. * @param boolean $direct - true to take only direct children
  196. * @param string $sortByField - field name to sort by
  197. * @param string $direction - sort direction : "ASC" or "DESC"
  198. * @throws InvalidArgumentException - if input is not valid
  199. * @return Query
  200. */
  201. public function childrenQuery($node = null, $direct = false, $sortByField = null, $direction = 'ASC')
  202. {
  203. $meta = $this->getClassMetadata();
  204. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  205. $qb = $this->_em->createQueryBuilder();
  206. $qb->select('node')
  207. ->from($config['useObjectClass'], 'node');
  208. if ($node !== null) {
  209. if ($node instanceof $meta->name) {
  210. $wrapped = new EntityWrapper($node, $this->_em);
  211. if (!$wrapped->hasValidIdentifier()) {
  212. throw new InvalidArgumentException("Node is not managed by UnitOfWork");
  213. }
  214. if ($direct) {
  215. $id = $wrapped->getIdentifier();
  216. $qb->where('node.' . $config['parent'] . ' = ' . $id);
  217. } else {
  218. $left = $wrapped->getPropertyValue($config['left']);
  219. $right = $wrapped->getPropertyValue($config['right']);
  220. if ($left && $right) {
  221. $qb->where('node.' . $config['right'] . " < {$right}")
  222. ->andWhere('node.' . $config['left'] . " > {$left}");
  223. }
  224. }
  225. if (isset($config['root'])) {
  226. $rootId = $wrapped->getPropertyValue($config['root']);
  227. $qb->andWhere("node.{$config['root']} = {$rootId}");
  228. }
  229. } else {
  230. throw new \InvalidArgumentException("Node is not related to this repository");
  231. }
  232. } else {
  233. if ($direct) {
  234. $qb->where('node.' . $config['parent'] . ' IS NULL');
  235. }
  236. }
  237. if (!$sortByField) {
  238. $qb->orderBy('node.' . $config['left'], 'ASC');
  239. } else {
  240. if ($meta->hasField($sortByField) && in_array(strtolower($direction), array('asc', 'desc'))) {
  241. $qb->orderBy('node.' . $sortByField, $direction);
  242. } else {
  243. throw new InvalidArgumentException("Invalid sort options specified: field - {$sortByField}, direction - {$direction}");
  244. }
  245. }
  246. return $qb->getQuery();
  247. }
  248. /**
  249. * Get list of children followed by given $node
  250. *
  251. * @param object $node - if null, all tree nodes will be taken
  252. * @param boolean $direct - true to take only direct children
  253. * @param string $sortByField - field name to sort by
  254. * @param string $direction - sort direction : "ASC" or "DESC"
  255. * @return array - list of given $node children, null on failure
  256. */
  257. public function children($node = null, $direct = false, $sortByField = null, $direction = 'ASC')
  258. {
  259. $q = $this->childrenQuery($node, $direct, $sortByField, $direction);
  260. return $q->getResult();
  261. }
  262. /**
  263. * Get tree leafs query
  264. *
  265. * @param object $root - root node in case of root tree is required
  266. * @param string $sortByField - field name to sort by
  267. * @param string $direction - sort direction : "ASC" or "DESC"
  268. * @throws InvalidArgumentException - if input is not valid
  269. * @return Query
  270. */
  271. public function getLeafsQuery($root = null, $sortByField = null, $direction = 'ASC')
  272. {
  273. $meta = $this->getClassMetadata();
  274. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  275. if (isset($config['root']) && is_null($root)) {
  276. if (is_null($root)) {
  277. throw new InvalidArgumentException("If tree has root, getLeafs method requires any node of this tree");
  278. }
  279. }
  280. $qb = $this->_em->createQueryBuilder();
  281. $qb->select('node')
  282. ->from($config['useObjectClass'], 'node')
  283. ->where('node.' . $config['right'] . ' = 1 + node.' . $config['left']);
  284. if (isset($config['root'])) {
  285. if ($root instanceof $meta->name) {
  286. $wrapped = new EntityWrapper($root, $this->_em);
  287. $rootId = $wrapped->getPropertyValue($config['root']);
  288. if (!$rootId) {
  289. throw new InvalidArgumentException("Root node must be managed");
  290. }
  291. $qb->andWhere("node.{$config['root']} = {$rootId}");
  292. } else {
  293. throw new InvalidArgumentException("Node is not related to this repository");
  294. }
  295. }
  296. if (!$sortByField) {
  297. $qb->orderBy('node.' . $config['left'], 'ASC');
  298. } else {
  299. if ($meta->hasField($sortByField) && in_array(strtolower($direction), array('asc', 'desc'))) {
  300. $qb->orderBy('node.' . $sortByField, $direction);
  301. } else {
  302. throw new InvalidArgumentException("Invalid sort options specified: field - {$sortByField}, direction - {$direction}");
  303. }
  304. }
  305. return $qb->getQuery();
  306. }
  307. /**
  308. * Get list of leaf nodes of the tree
  309. *
  310. * @param object $root - root node in case of root tree is required
  311. * @param string $sortByField - field name to sort by
  312. * @param string $direction - sort direction : "ASC" or "DESC"
  313. * @return array
  314. */
  315. public function getLeafs($root = null, $sortByField = null, $direction = 'ASC')
  316. {
  317. return $this->getLeafsQuery($root, $sortByField, $direction)->getResult();
  318. }
  319. /**
  320. * Get the query for next siblings of the given $node
  321. *
  322. * @param object $node
  323. * @param bool $includeSelf - include the node itself
  324. * @throws \Gedmo\Exception\InvalidArgumentException - if input is invalid
  325. * @return Query
  326. */
  327. public function getNextSiblingsQuery($node, $includeSelf = false)
  328. {
  329. $meta = $this->getClassMetadata();
  330. if (!$node instanceof $meta->name) {
  331. throw new InvalidArgumentException("Node is not related to this repository");
  332. }
  333. $wrapped = new EntityWrapper($node, $this->_em);
  334. if (!$wrapped->hasValidIdentifier()) {
  335. throw new InvalidArgumentException("Node is not managed by UnitOfWork");
  336. }
  337. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  338. $parent = $wrapped->getPropertyValue($config['parent']);
  339. if (isset($config['root']) && !$parent) {
  340. throw new InvalidArgumentException("Cannot get siblings from tree root node");
  341. }
  342. $left = $wrapped->getPropertyValue($config['left']);
  343. $sign = $includeSelf ? '>=' : '>';
  344. $dql = "SELECT node FROM {$config['useObjectClass']} node";
  345. if ($parent) {
  346. $wrappedParent = new EntityWrapper($parent, $this->_em);
  347. $parentId = $wrappedParent->getIdentifier();
  348. $dql .= " WHERE node.{$config['parent']} = {$parentId}";
  349. } else {
  350. $dql .= " WHERE node.{$config['parent']} IS NULL";
  351. }
  352. $dql .= " AND node.{$config['left']} {$sign} {$left}";
  353. $dql .= " ORDER BY node.{$config['left']} ASC";
  354. return $this->_em->createQuery($dql);
  355. }
  356. /**
  357. * Find the next siblings of the given $node
  358. *
  359. * @param object $node
  360. * @param bool $includeSelf - include the node itself
  361. * @return array
  362. */
  363. public function getNextSiblings($node, $includeSelf = false)
  364. {
  365. return $this->getNextSiblingsQuery($node, $includeSelf)->getResult();
  366. }
  367. /**
  368. * Get query for previous siblings of the given $node
  369. *
  370. * @param object $node
  371. * @param bool $includeSelf - include the node itself
  372. * @throws \Gedmo\Exception\InvalidArgumentException - if input is invalid
  373. * @return Query
  374. */
  375. public function getPrevSiblingsQuery($node, $includeSelf = false)
  376. {
  377. $meta = $this->getClassMetadata();
  378. if (!$node instanceof $meta->name) {
  379. throw new InvalidArgumentException("Node is not related to this repository");
  380. }
  381. $wrapped = new EntityWrapper($node, $this->_em);
  382. if (!$wrapped->hasValidIdentifier()) {
  383. throw new InvalidArgumentException("Node is not managed by UnitOfWork");
  384. }
  385. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  386. $parent = $wrapped->getPropertyValue($config['parent']);
  387. if (isset($config['root']) && !$parent) {
  388. throw new InvalidArgumentException("Cannot get siblings from tree root node");
  389. }
  390. $left = $wrapped->getPropertyValue($config['left']);
  391. $sign = $includeSelf ? '<=' : '<';
  392. $dql = "SELECT node FROM {$config['useObjectClass']} node";
  393. if ($parent) {
  394. $wrappedParent = new EntityWrapper($parent, $this->_em);
  395. $parentId = $wrappedParent->getIdentifier();
  396. $dql .= " WHERE node.{$config['parent']} = {$parentId}";
  397. } else {
  398. $dql .= " WHERE node.{$config['parent']} IS NULL";
  399. }
  400. $dql .= " AND node.{$config['left']} {$sign} {$left}";
  401. $dql .= " ORDER BY node.{$config['left']} ASC";
  402. return $this->_em->createQuery($dql);
  403. }
  404. /**
  405. * Find the previous siblings of the given $node
  406. *
  407. * @param object $node
  408. * @param bool $includeSelf - include the node itself
  409. * @return array
  410. */
  411. public function getPrevSiblings($node, $includeSelf = false)
  412. {
  413. return $this->getPrevSiblingsQuery($node, $includeSelf)->getResult();
  414. }
  415. /**
  416. * Move the node down in the same level
  417. *
  418. * @param object $node
  419. * @param mixed $number
  420. * integer - number of positions to shift
  421. * boolean - if "true" - shift till last position
  422. * @throws RuntimeException - if something fails in transaction
  423. * @return boolean - true if shifted
  424. */
  425. public function moveDown($node, $number = 1)
  426. {
  427. $result = false;
  428. $meta = $this->getClassMetadata();
  429. if ($node instanceof $meta->name) {
  430. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  431. $nextSiblings = $this->getNextSiblings($node);
  432. if ($numSiblings = count($nextSiblings)) {
  433. $result = true;
  434. if ($number === true) {
  435. $number = $numSiblings;
  436. } elseif ($number > $numSiblings) {
  437. $number = $numSiblings;
  438. }
  439. $this->listener
  440. ->getStrategy($this->_em, $meta->name)
  441. ->updateNode($this->_em, $node, $nextSiblings[$number - 1], Nested::NEXT_SIBLING);
  442. }
  443. } else {
  444. throw new InvalidArgumentException("Node is not related to this repository");
  445. }
  446. return $result;
  447. }
  448. /**
  449. * Move the node up in the same level
  450. *
  451. * @param object $node
  452. * @param mixed $number
  453. * integer - number of positions to shift
  454. * boolean - true shift till first position
  455. * @throws RuntimeException - if something fails in transaction
  456. * @return boolean - true if shifted
  457. */
  458. public function moveUp($node, $number = 1)
  459. {
  460. $result = false;
  461. $meta = $this->getClassMetadata();
  462. if ($node instanceof $meta->name) {
  463. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  464. $prevSiblings = array_reverse($this->getPrevSiblings($node));
  465. if ($numSiblings = count($prevSiblings)) {
  466. $result = true;
  467. if ($number === true) {
  468. $number = $numSiblings;
  469. } elseif ($number > $numSiblings) {
  470. $number = $numSiblings;
  471. }
  472. $this->listener
  473. ->getStrategy($this->_em, $meta->name)
  474. ->updateNode($this->_em, $node, $prevSiblings[$number - 1], Nested::PREV_SIBLING);
  475. }
  476. } else {
  477. throw new InvalidArgumentException("Node is not related to this repository");
  478. }
  479. return $result;
  480. }
  481. /**
  482. * Removes given $node from the tree and reparents its descendants
  483. *
  484. * @param object $node
  485. * @throws RuntimeException - if something fails in transaction
  486. * @return void
  487. */
  488. public function removeFromTree($node)
  489. {
  490. $meta = $this->getClassMetadata();
  491. if ($node instanceof $meta->name) {
  492. $wrapped = new EntityWrapper($node, $this->_em);
  493. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  494. $right = $wrapped->getPropertyValue($config['right']);
  495. $left = $wrapped->getPropertyValue($config['left']);
  496. $rootId = isset($config['root']) ? $wrapped->getPropertyValue($config['root']) : null;
  497. if ($right == $left + 1) {
  498. $this->removeSingle($wrapped);
  499. $this->listener
  500. ->getStrategy($this->_em, $meta->name)
  501. ->shiftRL($this->_em, $config['useObjectClass'], $right, -2, $rootId);
  502. return; // node was a leaf
  503. }
  504. // process updates in transaction
  505. $this->_em->getConnection()->beginTransaction();
  506. try {
  507. $parent = $wrapped->getPropertyValue($config['parent']);
  508. $parentId = 'NULL';
  509. if ($parent) {
  510. $wrappedParrent = new EntityWrapper($parent, $this->_em);
  511. $parentId = $wrappedParrent->getIdentifier();
  512. }
  513. $pk = $meta->getSingleIdentifierFieldName();
  514. $nodeId = $wrapped->getIdentifier();
  515. $shift = -1;
  516. // in case if root node is removed, childs become roots
  517. if (isset($config['root']) && !$parent) {
  518. $dql = "SELECT node.{$pk}, node.{$config['left']}, node.{$config['right']} FROM {$config['useObjectClass']} node";
  519. $dql .= " WHERE node.{$config['parent']} = {$nodeId}";
  520. $nodes = $this->_em->createQuery($dql)->getArrayResult();
  521. foreach ($nodes as $newRoot) {
  522. $left = $newRoot[$config['left']];
  523. $right = $newRoot[$config['right']];
  524. $rootId = $newRoot[$pk];
  525. $shift = -($left - 1);
  526. $dql = "UPDATE {$config['useObjectClass']} node";
  527. $dql .= ' SET node.' . $config['root'] . ' = :rootId';
  528. $dql .= ' WHERE node.' . $config['root'] . ' = :nodeId';
  529. $dql .= " AND node.{$config['left']} >= :left";
  530. $dql .= " AND node.{$config['right']} <= :right";
  531. $q = $this->_em->createQuery($dql);
  532. $q->setParameters(compact('rootId', 'left', 'right', 'nodeId'));
  533. $q->getSingleScalarResult();
  534. $dql = "UPDATE {$config['useObjectClass']} node";
  535. $dql .= ' SET node.' . $config['parent'] . ' = ' . $parentId;
  536. $dql .= ' WHERE node.' . $config['parent'] . ' = ' . $nodeId;
  537. $dql .= ' AND node.' . $config['root'] . ' = ' . $rootId;
  538. $q = $this->_em->createQuery($dql);
  539. $q->getSingleScalarResult();
  540. $this->listener
  541. ->getStrategy($this->_em, $meta->name)
  542. ->shiftRangeRL($this->_em, $config['useObjectClass'], $left, $right, $shift, $rootId, $rootId, - 1);
  543. $this->listener
  544. ->getStrategy($this->_em, $meta->name)
  545. ->shiftRL($this->_em, $config['useObjectClass'], $right, -2, $rootId);
  546. }
  547. } else {
  548. $dql = "UPDATE {$config['useObjectClass']} node";
  549. $dql .= ' SET node.' . $config['parent'] . ' = ' . $parentId;
  550. $dql .= ' WHERE node.' . $config['parent'] . ' = ' . $nodeId;
  551. if (isset($config['root'])) {
  552. $dql .= ' AND node.' . $config['root'] . ' = ' . $rootId;
  553. }
  554. // @todo: update in memory nodes
  555. $q = $this->_em->createQuery($dql);
  556. $q->getSingleScalarResult();
  557. $this->listener
  558. ->getStrategy($this->_em, $meta->name)
  559. ->shiftRangeRL($this->_em, $config['useObjectClass'], $left, $right, $shift, $rootId, $rootId, - 1);
  560. $this->listener
  561. ->getStrategy($this->_em, $meta->name)
  562. ->shiftRL($this->_em, $config['useObjectClass'], $right, -2, $rootId);
  563. }
  564. $this->removeSingle($wrapped);
  565. $this->_em->getConnection()->commit();
  566. } catch (\Exception $e) {
  567. $this->_em->close();
  568. $this->_em->getConnection()->rollback();
  569. throw new \Gedmo\Exception\RuntimeException('Transaction failed', null, $e);
  570. }
  571. } else {
  572. throw new InvalidArgumentException("Node is not related to this repository");
  573. }
  574. }
  575. /**
  576. * Reorders the sibling nodes and child nodes by given $node,
  577. * according to the $sortByField and $direction specified
  578. *
  579. * @param object $node - from which node to start reordering the tree
  580. * @param string $sortByField - field name to sort by
  581. * @param string $direction - sort direction : "ASC" or "DESC"
  582. * @param boolean $verify - true to verify tree first
  583. * @return void
  584. */
  585. public function reorder($node, $sortByField = null, $direction = 'ASC', $verify = true)
  586. {
  587. $meta = $this->getClassMetadata();
  588. if ($node instanceof $meta->name) {
  589. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  590. if ($verify && is_array($this->verify())) {
  591. return false;
  592. }
  593. $nodes = $this->children($node, true, $sortByField, $direction);
  594. foreach ($nodes as $node) {
  595. $wrapped = new EntityWrapper($node, $this->_em);
  596. $right = $wrapped->getPropertyValue($config['right']);
  597. $left = $wrapped->getPropertyValue($config['left']);
  598. $this->moveDown($node, true);
  599. if ($left != ($right - 1)) {
  600. $this->reorder($node, $sortByField, $direction, false);
  601. }
  602. }
  603. } else {
  604. throw new InvalidArgumentException("Node is not related to this repository");
  605. }
  606. }
  607. /**
  608. * Verifies that current tree is valid.
  609. * If any error is detected it will return an array
  610. * with a list of errors found on tree
  611. *
  612. * @return mixed
  613. * boolean - true on success
  614. * array - error list on failure
  615. */
  616. public function verify()
  617. {
  618. if (!$this->childCount()) {
  619. return true; // tree is empty
  620. }
  621. $errors = array();
  622. $meta = $this->getClassMetadata();
  623. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  624. if (isset($config['root'])) {
  625. $trees = $this->getRootNodes();
  626. foreach ($trees as $tree) {
  627. $this->verifyTree($errors, $tree);
  628. }
  629. } else {
  630. $this->verifyTree($errors);
  631. }
  632. return $errors ?: true;
  633. }
  634. /**
  635. * Tries to recover the tree
  636. *
  637. * @todo implement
  638. * @throws RuntimeException - if something fails in transaction
  639. * @return void
  640. */
  641. public function recover()
  642. {
  643. if ($this->verify() === true) {
  644. return;
  645. }
  646. // not yet implemented
  647. }
  648. /**
  649. * Retrieves the nested array or the html output
  650. *
  651. * @throws \Gedmo\Exception\InvalidArgumentException
  652. * @param object $node - from which node to start reordering the tree
  653. * @param boolean $direct - true to take only direct children
  654. * @param bool $html
  655. * @param array|null $options
  656. * @return array|string
  657. */
  658. public function childrenHierarchy($node = null, $direct = false, $html = false, array $options = null)
  659. {
  660. $meta = $this->getClassMetadata();
  661. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  662. if ($node !== null) {
  663. if ($node instanceof $meta->name) {
  664. $wrapped = new EntityWrapper($node, $this->_em);
  665. if (!$wrapped->hasValidIdentifier()) {
  666. throw new InvalidArgumentException("Node is not managed by UnitOfWork");
  667. }
  668. }
  669. }
  670. // Gets the array of $node results.
  671. // It must be order by 'root' field
  672. $nodes = self::childrenQuery(
  673. $node,
  674. $direct,
  675. isset($config['root']) ? $config['root'] : $config['left'],
  676. 'ASC'
  677. )->getArrayResult();
  678. return $this->buildTree($nodes, $html, $options);
  679. }
  680. /**
  681. * {@inheritdoc}
  682. */
  683. protected function validates()
  684. {
  685. return $this->listener->getStrategy($this->_em, $this->getClassMetadata()->name)->getName() === Strategy::NESTED;
  686. }
  687. /**
  688. * Collect errors on given tree if
  689. * where are any
  690. *
  691. * @param array $errors
  692. * @param object $root
  693. * @return void
  694. */
  695. private function verifyTree(&$errors, $root = null)
  696. {
  697. $meta = $this->getClassMetadata();
  698. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  699. $identifier = $meta->getSingleIdentifierFieldName();
  700. $rootId = isset($config['root']) ? $meta->getReflectionProperty($config['root'])->getValue($root) : null;
  701. $dql = "SELECT MIN(node.{$config['left']}) FROM {$config['useObjectClass']} node";
  702. if ($root) {
  703. $dql .= " WHERE node.{$config['root']} = {$rootId}";
  704. }
  705. $min = intval($this->_em->createQuery($dql)->getSingleScalarResult());
  706. $edge = $this->listener->getStrategy($this->_em, $meta->name)->max($this->_em, $config['useObjectClass'], $rootId);
  707. // check duplicate right and left values
  708. for ($i = $min; $i <= $edge; $i++) {
  709. $dql = "SELECT COUNT(node.{$identifier}) FROM {$config['useObjectClass']} node";
  710. $dql .= " WHERE (node.{$config['left']} = {$i} OR node.{$config['right']} = {$i})";
  711. if ($root) {
  712. $dql .= " AND node.{$config['root']} = {$rootId}";
  713. }
  714. $count = intval($this->_em->createQuery($dql)->getSingleScalarResult());
  715. if ($count !== 1) {
  716. if ($count === 0) {
  717. $errors[] = "index [{$i}], missing" . ($root ? ' on tree root: ' . $rootId : '');
  718. } else {
  719. $errors[] = "index [{$i}], duplicate" . ($root ? ' on tree root: ' . $rootId : '');
  720. }
  721. }
  722. }
  723. // check for missing parents
  724. $dql = "SELECT node FROM {$config['useObjectClass']} node";
  725. $dql .= " LEFT JOIN node.{$config['parent']} parent";
  726. $dql .= " WHERE node.{$config['parent']} IS NOT NULL";
  727. $dql .= " AND parent.{$identifier} IS NULL";
  728. if ($root) {
  729. $dql .= " AND node.{$config['root']} = {$rootId}";
  730. }
  731. $nodes = $this->_em->createQuery($dql)->getArrayResult();
  732. if (count($nodes)) {
  733. foreach ($nodes as $node) {
  734. $errors[] = "node [{$node[$identifier]}] has missing parent" . ($root ? ' on tree root: ' . $rootId : '');
  735. }
  736. return; // loading broken relation can cause infinite loop
  737. }
  738. $dql = "SELECT node FROM {$config['useObjectClass']} node";
  739. $dql .= " WHERE node.{$config['right']} < node.{$config['left']}";
  740. if ($root) {
  741. $dql .= " AND node.{$config['root']} = {$rootId}";
  742. }
  743. $result = $this->_em->createQuery($dql)
  744. ->setMaxResults(1)
  745. ->getResult(Query::HYDRATE_ARRAY);
  746. $node = count($result) ? array_shift($result) : null;
  747. if ($node) {
  748. $id = $node[$identifier];
  749. $errors[] = "node [{$id}], left is greater than right" . ($root ? ' on tree root: ' . $rootId : '');
  750. }
  751. $dql = "SELECT node FROM {$config['useObjectClass']} node";
  752. if ($root) {
  753. $dql .= " WHERE node.{$config['root']} = {$rootId}";
  754. }
  755. $nodes = $this->_em->createQuery($dql)->getResult(Query::HYDRATE_OBJECT);
  756. foreach ($nodes as $node) {
  757. $right = $meta->getReflectionProperty($config['right'])->getValue($node);
  758. $left = $meta->getReflectionProperty($config['left'])->getValue($node);
  759. $id = $meta->getReflectionProperty($identifier)->getValue($node);
  760. $parent = $meta->getReflectionProperty($config['parent'])->getValue($node);
  761. if (!$right || !$left) {
  762. $errors[] = "node [{$id}] has invalid left or right values";
  763. } elseif ($right == $left) {
  764. $errors[] = "node [{$id}] has identical left and right values";
  765. } elseif ($parent) {
  766. if ($parent instanceof Proxy && !$parent->__isInitialized__) {
  767. $this->_em->refresh($parent);
  768. }
  769. $parentRight = $meta->getReflectionProperty($config['right'])->getValue($parent);
  770. $parentLeft = $meta->getReflectionProperty($config['left'])->getValue($parent);
  771. $parentId = $meta->getReflectionProperty($identifier)->getValue($parent);
  772. if ($left < $parentLeft) {
  773. $errors[] = "node [{$id}] left is less than parent`s [{$parentId}] left value";
  774. } elseif ($right > $parentRight) {
  775. $errors[] = "node [{$id}] right is greater than parent`s [{$parentId}] right value";
  776. }
  777. } else {
  778. $dql = "SELECT COUNT(node.{$identifier}) FROM {$config['useObjectClass']} node";
  779. $dql .= " WHERE node.{$config['left']} < {$left}";
  780. $dql .= " AND node.{$config['right']} > {$right}";
  781. if ($root) {
  782. $dql .= " AND node.{$config['root']} = {$rootId}";
  783. }
  784. $q = $this->_em->createQuery($dql);
  785. if ($count = intval($q->getSingleScalarResult())) {
  786. $errors[] = "node [{$id}] parent field is blank, but it has a parent";
  787. }
  788. }
  789. }
  790. }
  791. /**
  792. * Removes single node without touching children
  793. *
  794. * @internal
  795. * @param EntityWrapper $wrapped
  796. * @return void
  797. */
  798. private function removeSingle(EntityWrapper $wrapped)
  799. {
  800. $meta = $this->getClassMetadata();
  801. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  802. $pk = $meta->getSingleIdentifierFieldName();
  803. $nodeId = $wrapped->getIdentifier();
  804. // prevent from deleting whole branch
  805. $dql = "UPDATE {$config['useObjectClass']} node";
  806. $dql .= ' SET node.' . $config['left'] . ' = 0,';
  807. $dql .= ' node.' . $config['right'] . ' = 0';
  808. $dql .= ' WHERE node.' . $pk . ' = ' . $nodeId;
  809. $this->_em->createQuery($dql)->getSingleScalarResult();
  810. // remove the node from database
  811. $dql = "DELETE {$config['useObjectClass']} node";
  812. $dql .= " WHERE node.{$pk} = {$nodeId}";
  813. $this->_em->createQuery($dql)->getSingleScalarResult();
  814. // remove from identity map
  815. $this->_em->getUnitOfWork()->removeFromIdentityMap($wrapped->getObject());
  816. }
  817. /**
  818. * Builds the tree
  819. *
  820. * @param array $nodes
  821. * @param bool $html
  822. * @param array|null $options
  823. * @return array|string
  824. */
  825. private function buildTree(array $nodes, $html = false, array $options = null)
  826. {
  827. //process the nested tree into a nested array
  828. $config = $this->listener->getConfiguration($this->_em, $this->getClassMetadata()->name);
  829. $nestedTree = $this->processTree($nodes, $config);
  830. // If you don't want any html output it will return the nested array
  831. if (!$html) {
  832. return $nestedTree;
  833. }
  834. //Defines html decorators and opcional options
  835. if (!empty($options['root'])) {
  836. $root_open = $options['root']['open'];
  837. $root_close = $options['root']['close'];
  838. } else {
  839. $root_open = "<ul> ";
  840. $root_close = " </ul>";
  841. }
  842. if (!empty($options['child'])) {
  843. $child_open = $options['child']['open'];
  844. $child_close = $options['child']['close'];
  845. } else {
  846. $child_open = "<li> ";
  847. $child_close = " </li>";
  848. }
  849. $representationField = empty($options['representationField']) ?
  850. 'title' :
  851. $options['representationField']
  852. ;
  853. if (!$this->getClassMetadata()->hasField($representationField) && $html) {
  854. throw new InvalidArgumentException("There must be a representation field specified");
  855. }
  856. $html_decorator = array(
  857. 'root' => array('open' => $root_open, 'close' => $root_close),
  858. 'child' => array('open' => $child_open, 'close' => $child_close),
  859. 'represents' => $representationField
  860. );
  861. $html_output = $this->processHtmlTree($nestedTree, $html_decorator, $html_output = null);
  862. return $html_output;
  863. }
  864. /**
  865. * Creates the nested array
  866. *
  867. * @static
  868. * @param array $nodes
  869. * @return array
  870. */
  871. private static function processTree(array $nodes, array $config)
  872. {
  873. // Trees mapped
  874. $trees = array();
  875. $l = 0;
  876. if (count($nodes) > 0) {
  877. // Node Stack. Used to help building the hierarchy
  878. $stack = array();
  879. foreach ($nodes as $child) {
  880. $item = $child;
  881. $item['children'] = array();
  882. // Number of stack items
  883. $l = count($stack);
  884. // Check if we're dealing with different levels
  885. while($l > 0 && $stack[$l - 1][$config['level']] >= $item[$config['level']]) {
  886. array_pop($stack);
  887. $l--;
  888. }
  889. // Stack is empty (we are inspecting the root)
  890. if ($l == 0) {
  891. // Assigning the root child
  892. $i = count($trees);
  893. $trees[$i] = $item;
  894. $stack[] = & $trees[$i];
  895. } else {
  896. // Add child to parent
  897. $i = count($stack[$l - 1]['children']);
  898. $stack[$l - 1]['children'][$i] = $item;
  899. $stack[] = & $stack[$l - 1]['children'][$i];
  900. }
  901. }
  902. }
  903. return $trees;
  904. }
  905. /**
  906. * Creates the html output of the nested tree
  907. *
  908. * @param $parent_node
  909. * @param $html_decorator
  910. * @param $html_output
  911. * @return string
  912. */
  913. private function processHtmlTree($parent_node, $html_decorator, $html_output)
  914. {
  915. if (is_array($parent_node)) {
  916. $html_output .= $html_decorator['root']['open'];
  917. foreach ($parent_node as $item) {
  918. $html_output .= $html_decorator['child']['open'] . $item[$html_decorator['represents']];
  919. if (count($item['children']) > 0) {
  920. $html_output = $this->processHtmlTree($item['children'], $html_decorator, $html_output);
  921. }
  922. $html_output .= $html_decorator['child']['close'];
  923. }
  924. $html_output .= $html_decorator['root']['close'];
  925. }
  926. return $html_output;
  927. }
  928. }