NestedTreeRepository.php 48 KB

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