NestedTreeRepository.php 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059
  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 (false) - 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 > 0 && $stack[$l - 1][$config['level']] >= $item[$config['level']]) {
  931. array_pop($stack);
  932. $l--;
  933. }
  934. // Stack is empty (we are inspecting the root)
  935. if ($l == 0) {
  936. // Assigning the root child
  937. $i = count($nestedTree);
  938. $nestedTree[$i] = $item;
  939. $stack[] = &$nestedTree[$i];
  940. } else {
  941. // Add child to parent
  942. $i = count($stack[$l - 1]['__children']);
  943. $stack[$l - 1]['__children'][$i] = $item;
  944. $stack[] = &$stack[$l - 1]['__children'][$i];
  945. }
  946. }
  947. }
  948. $default = array(
  949. 'decorate' => false,
  950. 'rootOpen' => '<ul>',
  951. 'rootClose' => '</ul>',
  952. 'childOpen' => '<li>',
  953. 'childClose' => '</li>',
  954. 'nodeDecorator' => function ($node) use ($meta) {
  955. // override and change it, guessing which field to use
  956. if ($meta->hasField('title')) {
  957. $field = 'title';
  958. } else if ($meta->hasField('name')) {
  959. $field = 'name';
  960. } else {
  961. throw new InvalidArgumentException("Cannot find any representation field");
  962. }
  963. return $node[$field];
  964. }
  965. );
  966. $options = array_merge($default, $options);
  967. // If you don't want any html output it will return the nested array
  968. if (!$options['decorate'] || !count($nestedTree)) {
  969. return $nestedTree;
  970. }
  971. $build = function($tree) use (&$build, &$options) {
  972. $output = $options['rootOpen'];
  973. foreach ($tree as $node) {
  974. $output .= $options['childOpen'] . $options['nodeDecorator']($node);
  975. if (count($node['__children']) > 0) {
  976. $output .= $build($node['__children']);
  977. }
  978. $output .= $options['childClose'];
  979. }
  980. return $output . $options['rootClose'];
  981. };
  982. return $build($nestedTree);
  983. }
  984. }