NestedTreeRepository.php 41 KB

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