NestedTreeRepository.php 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  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 html output
  733. *
  734. * @throws \Gedmo\Exception\InvalidArgumentException
  735. * @param object $node - from which node to start reordering the tree
  736. * @param boolean $direct - true to take only direct children
  737. * @param bool $html
  738. * @param array|null $options
  739. * @return array|string
  740. */
  741. public function childrenHierarchy($node = null, $direct = false, $html = false, array $options = null)
  742. {
  743. $meta = $this->getClassMetadata();
  744. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  745. if ($node !== null) {
  746. if ($node instanceof $meta->name) {
  747. $wrapped = new EntityWrapper($node, $this->_em);
  748. if (!$wrapped->hasValidIdentifier()) {
  749. throw new InvalidArgumentException("Node is not managed by UnitOfWork");
  750. }
  751. }
  752. }
  753. // Gets the array of $node results.
  754. // It must be order by 'root' and 'left' field
  755. $nodes = self::childrenQuery(
  756. $node,
  757. $direct,
  758. isset($config['root']) ? array($config['root'], $config['left']) : $config['left'],
  759. 'ASC'
  760. )->getArrayResult();
  761. return $this->buildTree($nodes, $html, $options);
  762. }
  763. /**
  764. * {@inheritdoc}
  765. */
  766. protected function validates()
  767. {
  768. return $this->listener->getStrategy($this->_em, $this->getClassMetadata()->name)->getName() === Strategy::NESTED;
  769. }
  770. /**
  771. * Collect errors on given tree if
  772. * where are any
  773. *
  774. * @param array $errors
  775. * @param object $root
  776. * @return void
  777. */
  778. private function verifyTree(&$errors, $root = null)
  779. {
  780. $meta = $this->getClassMetadata();
  781. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  782. $identifier = $meta->getSingleIdentifierFieldName();
  783. $rootId = isset($config['root']) ? $meta->getReflectionProperty($config['root'])->getValue($root) : null;
  784. $dql = "SELECT MIN(node.{$config['left']}) FROM {$config['useObjectClass']} node";
  785. if ($root) {
  786. $dql .= " WHERE node.{$config['root']} = {$rootId}";
  787. }
  788. $min = intval($this->_em->createQuery($dql)->getSingleScalarResult());
  789. $edge = $this->listener->getStrategy($this->_em, $meta->name)->max($this->_em, $config['useObjectClass'], $rootId);
  790. // check duplicate right and left values
  791. for ($i = $min; $i <= $edge; $i++) {
  792. $dql = "SELECT COUNT(node.{$identifier}) FROM {$config['useObjectClass']} node";
  793. $dql .= " WHERE (node.{$config['left']} = {$i} OR node.{$config['right']} = {$i})";
  794. if ($root) {
  795. $dql .= " AND node.{$config['root']} = {$rootId}";
  796. }
  797. $count = intval($this->_em->createQuery($dql)->getSingleScalarResult());
  798. if ($count !== 1) {
  799. if ($count === 0) {
  800. $errors[] = "index [{$i}], missing" . ($root ? ' on tree root: ' . $rootId : '');
  801. } else {
  802. $errors[] = "index [{$i}], duplicate" . ($root ? ' on tree root: ' . $rootId : '');
  803. }
  804. }
  805. }
  806. // check for missing parents
  807. $dql = "SELECT node FROM {$config['useObjectClass']} node";
  808. $dql .= " LEFT JOIN node.{$config['parent']} parent";
  809. $dql .= " WHERE node.{$config['parent']} IS NOT NULL";
  810. $dql .= " AND parent.{$identifier} IS NULL";
  811. if ($root) {
  812. $dql .= " AND node.{$config['root']} = {$rootId}";
  813. }
  814. $nodes = $this->_em->createQuery($dql)->getArrayResult();
  815. if (count($nodes)) {
  816. foreach ($nodes as $node) {
  817. $errors[] = "node [{$node[$identifier]}] has missing parent" . ($root ? ' on tree root: ' . $rootId : '');
  818. }
  819. return; // loading broken relation can cause infinite loop
  820. }
  821. $dql = "SELECT node FROM {$config['useObjectClass']} node";
  822. $dql .= " WHERE node.{$config['right']} < node.{$config['left']}";
  823. if ($root) {
  824. $dql .= " AND node.{$config['root']} = {$rootId}";
  825. }
  826. $result = $this->_em->createQuery($dql)
  827. ->setMaxResults(1)
  828. ->getResult(Query::HYDRATE_ARRAY);
  829. $node = count($result) ? array_shift($result) : null;
  830. if ($node) {
  831. $id = $node[$identifier];
  832. $errors[] = "node [{$id}], left is greater than right" . ($root ? ' on tree root: ' . $rootId : '');
  833. }
  834. $dql = "SELECT node FROM {$config['useObjectClass']} node";
  835. if ($root) {
  836. $dql .= " WHERE node.{$config['root']} = {$rootId}";
  837. }
  838. $nodes = $this->_em->createQuery($dql)->getResult(Query::HYDRATE_OBJECT);
  839. foreach ($nodes as $node) {
  840. $right = $meta->getReflectionProperty($config['right'])->getValue($node);
  841. $left = $meta->getReflectionProperty($config['left'])->getValue($node);
  842. $id = $meta->getReflectionProperty($identifier)->getValue($node);
  843. $parent = $meta->getReflectionProperty($config['parent'])->getValue($node);
  844. if (!$right || !$left) {
  845. $errors[] = "node [{$id}] has invalid left or right values";
  846. } elseif ($right == $left) {
  847. $errors[] = "node [{$id}] has identical left and right values";
  848. } elseif ($parent) {
  849. if ($parent instanceof Proxy && !$parent->__isInitialized__) {
  850. $this->_em->refresh($parent);
  851. }
  852. $parentRight = $meta->getReflectionProperty($config['right'])->getValue($parent);
  853. $parentLeft = $meta->getReflectionProperty($config['left'])->getValue($parent);
  854. $parentId = $meta->getReflectionProperty($identifier)->getValue($parent);
  855. if ($left < $parentLeft) {
  856. $errors[] = "node [{$id}] left is less than parent`s [{$parentId}] left value";
  857. } elseif ($right > $parentRight) {
  858. $errors[] = "node [{$id}] right is greater than parent`s [{$parentId}] right value";
  859. }
  860. } else {
  861. $dql = "SELECT COUNT(node.{$identifier}) FROM {$config['useObjectClass']} node";
  862. $dql .= " WHERE node.{$config['left']} < {$left}";
  863. $dql .= " AND node.{$config['right']} > {$right}";
  864. if ($root) {
  865. $dql .= " AND node.{$config['root']} = {$rootId}";
  866. }
  867. $q = $this->_em->createQuery($dql);
  868. if ($count = intval($q->getSingleScalarResult())) {
  869. $errors[] = "node [{$id}] parent field is blank, but it has a parent";
  870. }
  871. }
  872. }
  873. }
  874. /**
  875. * Removes single node without touching children
  876. *
  877. * @internal
  878. * @param EntityWrapper $wrapped
  879. * @return void
  880. */
  881. private function removeSingle(EntityWrapper $wrapped)
  882. {
  883. $meta = $this->getClassMetadata();
  884. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  885. $pk = $meta->getSingleIdentifierFieldName();
  886. $nodeId = $wrapped->getIdentifier();
  887. // prevent from deleting whole branch
  888. $dql = "UPDATE {$config['useObjectClass']} node";
  889. $dql .= ' SET node.' . $config['left'] . ' = 0,';
  890. $dql .= ' node.' . $config['right'] . ' = 0';
  891. $dql .= ' WHERE node.' . $pk . ' = ' . $nodeId;
  892. $this->_em->createQuery($dql)->getSingleScalarResult();
  893. // remove the node from database
  894. $dql = "DELETE {$config['useObjectClass']} node";
  895. $dql .= " WHERE node.{$pk} = {$nodeId}";
  896. $this->_em->createQuery($dql)->getSingleScalarResult();
  897. // remove from identity map
  898. $this->_em->getUnitOfWork()->removeFromIdentityMap($wrapped->getObject());
  899. }
  900. /**
  901. * Builds the tree
  902. *
  903. * @param array $nodes
  904. * @param bool $html
  905. * @param array|null $options
  906. * @return array|string
  907. */
  908. private function buildTree(array $nodes, $html = false, array $options = null)
  909. {
  910. //process the nested tree into a nested array
  911. $config = $this->listener->getConfiguration($this->_em, $this->getClassMetadata()->name);
  912. $nestedTree = $this->processTree($nodes, $config);
  913. // If you don't want any html output it will return the nested array
  914. if (!$html) {
  915. return $nestedTree;
  916. }
  917. //Defines html decorators and opcional options
  918. if (!empty($options['root'])) {
  919. $root_open = $options['root']['open'];
  920. $root_close = $options['root']['close'];
  921. } else {
  922. $root_open = "<ul> ";
  923. $root_close = " </ul>";
  924. }
  925. if (!empty($options['child'])) {
  926. $child_open = $options['child']['open'];
  927. $child_close = $options['child']['close'];
  928. } else {
  929. $child_open = "<li> ";
  930. $child_close = " </li>";
  931. }
  932. $representationField = empty($options['representationField']) ?
  933. 'title' :
  934. $options['representationField']
  935. ;
  936. if (!$this->getClassMetadata()->hasField($representationField) && $html) {
  937. throw new InvalidArgumentException("There must be a representation field specified");
  938. }
  939. $html_decorator = array(
  940. 'root' => array('open' => $root_open, 'close' => $root_close),
  941. 'child' => array('open' => $child_open, 'close' => $child_close),
  942. 'represents' => $representationField
  943. );
  944. $html_output = $this->processHtmlTree($nestedTree, $html_decorator, $html_output = null);
  945. return $html_output;
  946. }
  947. /**
  948. * Creates the nested array
  949. *
  950. * @static
  951. * @param array $nodes
  952. * @return array
  953. */
  954. private static function processTree(array $nodes, array $config)
  955. {
  956. // Trees mapped
  957. $trees = array();
  958. $l = 0;
  959. if (count($nodes) > 0) {
  960. // Node Stack. Used to help building the hierarchy
  961. $stack = array();
  962. foreach ($nodes as $child) {
  963. $item = $child;
  964. $item['children'] = array();
  965. // Number of stack items
  966. $l = count($stack);
  967. // Check if we're dealing with different levels
  968. while($l > 0 && $stack[$l - 1][$config['level']] >= $item[$config['level']]) {
  969. array_pop($stack);
  970. $l--;
  971. }
  972. // Stack is empty (we are inspecting the root)
  973. if ($l == 0) {
  974. // Assigning the root child
  975. $i = count($trees);
  976. $trees[$i] = $item;
  977. $stack[] = & $trees[$i];
  978. } else {
  979. // Add child to parent
  980. $i = count($stack[$l - 1]['children']);
  981. $stack[$l - 1]['children'][$i] = $item;
  982. $stack[] = & $stack[$l - 1]['children'][$i];
  983. }
  984. }
  985. }
  986. return $trees;
  987. }
  988. /**
  989. * Creates the html output of the nested tree
  990. *
  991. * @param $parent_node
  992. * @param $html_decorator
  993. * @param $html_output
  994. * @return string
  995. */
  996. private function processHtmlTree($parent_node, $html_decorator, $html_output)
  997. {
  998. if (is_array($parent_node)) {
  999. $html_output .= $html_decorator['root']['open'];
  1000. foreach ($parent_node as $item) {
  1001. $html_output .= $html_decorator['child']['open'] . $item[$html_decorator['represents']];
  1002. if (count($item['children']) > 0) {
  1003. $html_output = $this->processHtmlTree($item['children'], $html_decorator, $html_output);
  1004. }
  1005. $html_output .= $html_decorator['child']['close'];
  1006. }
  1007. $html_output .= $html_decorator['root']['close'];
  1008. }
  1009. return $html_output;
  1010. }
  1011. }