NestedTreeRepository.php 42 KB

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