NestedTreeRepository.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  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, getLiefs 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. * {@inheritdoc}
  650. */
  651. protected function validates()
  652. {
  653. return $this->listener->getStrategy($this->_em, $this->getClassMetadata()->name)->getName() === Strategy::NESTED;
  654. }
  655. /**
  656. * Collect errors on given tree if
  657. * where are any
  658. *
  659. * @param array $errors
  660. * @param object $root
  661. * @return void
  662. */
  663. private function verifyTree(&$errors, $root = null)
  664. {
  665. $meta = $this->getClassMetadata();
  666. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  667. $identifier = $meta->getSingleIdentifierFieldName();
  668. $rootId = isset($config['root']) ? $meta->getReflectionProperty($config['root'])->getValue($root) : null;
  669. $dql = "SELECT MIN(node.{$config['left']}) FROM {$config['useObjectClass']} node";
  670. if ($root) {
  671. $dql .= " WHERE node.{$config['root']} = {$rootId}";
  672. }
  673. $min = intval($this->_em->createQuery($dql)->getSingleScalarResult());
  674. $edge = $this->listener->getStrategy($this->_em, $meta->name)->max($this->_em, $config['useObjectClass'], $rootId);
  675. // check duplicate right and left values
  676. for ($i = $min; $i <= $edge; $i++) {
  677. $dql = "SELECT COUNT(node.{$identifier}) FROM {$config['useObjectClass']} node";
  678. $dql .= " WHERE (node.{$config['left']} = {$i} OR node.{$config['right']} = {$i})";
  679. if ($root) {
  680. $dql .= " AND node.{$config['root']} = {$rootId}";
  681. }
  682. $count = intval($this->_em->createQuery($dql)->getSingleScalarResult());
  683. if ($count !== 1) {
  684. if ($count === 0) {
  685. $errors[] = "index [{$i}], missing" . ($root ? ' on tree root: ' . $rootId : '');
  686. } else {
  687. $errors[] = "index [{$i}], duplicate" . ($root ? ' on tree root: ' . $rootId : '');
  688. }
  689. }
  690. }
  691. // check for missing parents
  692. $dql = "SELECT node FROM {$config['useObjectClass']} node";
  693. $dql .= " LEFT JOIN node.{$config['parent']} parent";
  694. $dql .= " WHERE node.{$config['parent']} IS NOT NULL";
  695. $dql .= " AND parent.{$identifier} IS NULL";
  696. if ($root) {
  697. $dql .= " AND node.{$config['root']} = {$rootId}";
  698. }
  699. $nodes = $this->_em->createQuery($dql)->getArrayResult();
  700. if (count($nodes)) {
  701. foreach ($nodes as $node) {
  702. $errors[] = "node [{$node[$identifier]}] has missing parent" . ($root ? ' on tree root: ' . $rootId : '');
  703. }
  704. return; // loading broken relation can cause infinite loop
  705. }
  706. $dql = "SELECT node FROM {$config['useObjectClass']} node";
  707. $dql .= " WHERE node.{$config['right']} < node.{$config['left']}";
  708. if ($root) {
  709. $dql .= " AND node.{$config['root']} = {$rootId}";
  710. }
  711. $result = $this->_em->createQuery($dql)
  712. ->setMaxResults(1)
  713. ->getResult(Query::HYDRATE_ARRAY);
  714. $node = count($result) ? array_shift($result) : null;
  715. if ($node) {
  716. $id = $node[$identifier];
  717. $errors[] = "node [{$id}], left is greater than right" . ($root ? ' on tree root: ' . $rootId : '');
  718. }
  719. $dql = "SELECT node FROM {$config['useObjectClass']} node";
  720. if ($root) {
  721. $dql .= " WHERE node.{$config['root']} = {$rootId}";
  722. }
  723. $nodes = $this->_em->createQuery($dql)->getResult(Query::HYDRATE_OBJECT);
  724. foreach ($nodes as $node) {
  725. $right = $meta->getReflectionProperty($config['right'])->getValue($node);
  726. $left = $meta->getReflectionProperty($config['left'])->getValue($node);
  727. $id = $meta->getReflectionProperty($identifier)->getValue($node);
  728. $parent = $meta->getReflectionProperty($config['parent'])->getValue($node);
  729. if (!$right || !$left) {
  730. $errors[] = "node [{$id}] has invalid left or right values";
  731. } elseif ($right == $left) {
  732. $errors[] = "node [{$id}] has identical left and right values";
  733. } elseif ($parent) {
  734. if ($parent instanceof Proxy && !$parent->__isInitialized__) {
  735. $this->_em->refresh($parent);
  736. }
  737. $parentRight = $meta->getReflectionProperty($config['right'])->getValue($parent);
  738. $parentLeft = $meta->getReflectionProperty($config['left'])->getValue($parent);
  739. $parentId = $meta->getReflectionProperty($identifier)->getValue($parent);
  740. if ($left < $parentLeft) {
  741. $errors[] = "node [{$id}] left is less than parent`s [{$parentId}] left value";
  742. } elseif ($right > $parentRight) {
  743. $errors[] = "node [{$id}] right is greater than parent`s [{$parentId}] right value";
  744. }
  745. } else {
  746. $dql = "SELECT COUNT(node.{$identifier}) FROM {$config['useObjectClass']} node";
  747. $dql .= " WHERE node.{$config['left']} < {$left}";
  748. $dql .= " AND node.{$config['right']} > {$right}";
  749. if ($root) {
  750. $dql .= " AND node.{$config['root']} = {$rootId}";
  751. }
  752. $q = $this->_em->createQuery($dql);
  753. if ($count = intval($q->getSingleScalarResult())) {
  754. $errors[] = "node [{$id}] parent field is blank, but it has a parent";
  755. }
  756. }
  757. }
  758. }
  759. /**
  760. * Removes single node without touching children
  761. *
  762. * @internal
  763. * @param EntityWrapper $wrapped
  764. * @return void
  765. */
  766. private function removeSingle(EntityWrapper $wrapped)
  767. {
  768. $meta = $this->getClassMetadata();
  769. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  770. $pk = $meta->getSingleIdentifierFieldName();
  771. $nodeId = $wrapped->getIdentifier();
  772. // prevent from deleting whole branch
  773. $dql = "UPDATE {$config['useObjectClass']} node";
  774. $dql .= ' SET node.' . $config['left'] . ' = 0,';
  775. $dql .= ' node.' . $config['right'] . ' = 0';
  776. $dql .= ' WHERE node.' . $pk . ' = ' . $nodeId;
  777. $this->_em->createQuery($dql)->getSingleScalarResult();
  778. // remove the node from database
  779. $dql = "DELETE {$config['useObjectClass']} node";
  780. $dql .= " WHERE node.{$pk} = {$nodeId}";
  781. $this->_em->createQuery($dql)->getSingleScalarResult();
  782. // remove from identity map
  783. $this->_em->getUnitOfWork()->removeFromIdentityMap($wrapped->getObject());
  784. }
  785. /**
  786. * Retrieves the nested array or the html output
  787. *
  788. * @throws \Gedmo\Exception\InvalidArgumentException
  789. * @param object $node - from which node to start reordering the tree
  790. * @param boolean $direct - true to take only direct children
  791. * @param bool $html
  792. * @param array|null $options
  793. * @return array|string
  794. */
  795. public function childrenHierarchy($node = null, $direct = false, $html = false, array $options = null)
  796. {
  797. $meta = $this->getClassMetadata();
  798. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  799. if ($node !== null) {
  800. if ($node instanceof $meta->name) {
  801. $wrapped = new EntityWrapper($node, $this->_em);
  802. if (!$wrapped->hasValidIdentifier()) {
  803. throw new InvalidArgumentException("Node is not managed by UnitOfWork");
  804. }
  805. }
  806. }
  807. // Gets the array of $node results.
  808. // It must be order by 'root' field
  809. $nodes = self::childrenQuery($node, $direct, 'root' , 'ASC')->getArrayResult();
  810. return $this->buildTree($nodes, $html, $options);
  811. }
  812. /**
  813. * Builds the tree
  814. *
  815. * @param array $nodes
  816. * @param bool $html
  817. * @param array|null $options
  818. * @return array|string
  819. */
  820. private function buildTree(array $nodes, $html = false, array $options = null)
  821. {
  822. //process the nested tree into a nested array
  823. $nestedTree = $this->processTree($nodes);
  824. // If you don't want any html output it will return the nested array
  825. if(!$html){
  826. return $nestedTree;
  827. }
  828. //Defines html decorators and opcional options
  829. if(!empty($options['root'])){
  830. $root_open = $options['root']['open'];
  831. $root_close = $options['root']['close'];
  832. }else{
  833. $root_open = "<ul> ";
  834. $root_close = " </ul>";
  835. if(!empty($options['child'])){
  836. $child_open = $options['child']['open'];
  837. $child_close = $options['child']['close'];
  838. }else{
  839. $child_open = "<li> ";
  840. $child_close = " </li>";
  841. }
  842. }
  843. $html_decorator = array(
  844. 'root' => array('open' => $root_open, 'close' => $root_close),
  845. 'child' => array('open' => $child_open, 'close' => $child_close),
  846. );
  847. $html_output = $this->processHtmlTree($nestedTree, $html_decorator, $html_output = null);
  848. return $html_output;
  849. }
  850. /**
  851. * Creates the nested array
  852. *
  853. * @static
  854. * @param array $nodes
  855. * @return array
  856. */
  857. private static function processTree($nodes)
  858. {
  859. // Trees mapped
  860. $trees = array();
  861. $l = 0;
  862. if (count($nodes) > 0) {
  863. // Node Stack. Used to help building the hierarchy
  864. $stack = array();
  865. foreach ($nodes as $child) {
  866. $item = $child;
  867. $item['children'] = array();
  868. // Number of stack items
  869. $l = count($stack);
  870. // Check if we're dealing with different levels
  871. while($l > 0 && $stack[$l - 1]['lvl'] >= $item['lvl']) {
  872. array_pop($stack);
  873. $l--;
  874. }
  875. // Stack is empty (we are inspecting the root)
  876. if ($l == 0) {
  877. // Assigning the root child
  878. $i = count($trees);
  879. $trees[$i] = $item;
  880. $stack[] = & $trees[$i];
  881. } else {
  882. // Add child to parent
  883. $i = count($stack[$l - 1]['children']);
  884. $stack[$l - 1]['children'][$i] = $item;
  885. $stack[] = & $stack[$l - 1]['children'][$i];
  886. }
  887. }
  888. }
  889. return $trees;
  890. }
  891. /**
  892. * Creates the html output of the nested tree
  893. *
  894. * @param $parent_node
  895. * @param $html_decorator
  896. * @param $html_output
  897. * @return string
  898. */
  899. private function processHtmlTree($parent_node, $html_decorator, $html_output)
  900. {
  901. if (is_array($parent_node)) {
  902. $html_output .= $html_decorator['root']['open'];
  903. foreach ($parent_node as $item) {
  904. $html_output .= $html_decorator['child']['open'] . $item['title'];
  905. if (count($item['children']) > 0) {
  906. $html_output = $this->processHtmlTree($item['children'], $html_decorator, $html_output);
  907. }
  908. $html_output .= $html_decorator['child']['close'];
  909. }
  910. $html_output .= $html_decorator['root']['close'];
  911. }
  912. return $html_output;
  913. }
  914. }