NestedTreeRepository.php 33 KB

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