NestedTreeRepository.php 31 KB

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