NestedTreeRepository.php 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  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 the sibling nodes and child nodes by given $node,
  673. * according to the $sortByField and $direction specified
  674. *
  675. * @param object $node - from which node to start reordering the tree
  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) {
  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. * Verifies that current tree is valid.
  705. * If any error is detected it will return an array
  706. * with a list of errors found on tree
  707. *
  708. * @return mixed
  709. * boolean - true on success
  710. * array - error list on failure
  711. */
  712. public function verify()
  713. {
  714. if (!$this->childCount()) {
  715. return true; // tree is empty
  716. }
  717. $errors = array();
  718. $meta = $this->getClassMetadata();
  719. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  720. if (isset($config['root'])) {
  721. $trees = $this->getRootNodes();
  722. foreach ($trees as $tree) {
  723. $this->verifyTree($errors, $tree);
  724. }
  725. } else {
  726. $this->verifyTree($errors);
  727. }
  728. return $errors ?: true;
  729. }
  730. /**
  731. * Tries to recover the tree
  732. *
  733. * @todo implement
  734. * @throws RuntimeException - if something fails in transaction
  735. * @return void
  736. */
  737. public function recover()
  738. {
  739. if ($this->verify() === true) {
  740. return;
  741. }
  742. // not yet implemented
  743. }
  744. /**
  745. * {@inheritDoc}
  746. */
  747. public function getNodesHierarchyQueryBuilder($node = null, $direct = false, array $options = array(), $includeNode = false)
  748. {
  749. $meta = $this->getClassMetadata();
  750. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  751. return $this->childrenQueryBuilder(
  752. $node,
  753. $direct,
  754. isset($config['root']) ? array($config['root'], $config['left']) : $config['left'],
  755. 'ASC',
  756. $includeNode
  757. );
  758. }
  759. /**
  760. * {@inheritDoc}
  761. */
  762. public function getNodesHierarchyQuery($node = null, $direct = false, array $options = array(), $includeNode = false)
  763. {
  764. return $this->getNodesHierarchyQueryBuilder($node, $direct, $options, $includeNode)->getQuery();
  765. }
  766. /**
  767. * {@inheritdoc}
  768. */
  769. public function getNodesHierarchy($node = null, $direct = false, array $options = array(), $includeNode = false)
  770. {
  771. return $this->getNodesHierarchyQuery($node, $direct, $options, $includeNode)->getArrayResult();
  772. }
  773. /**
  774. * {@inheritdoc}
  775. */
  776. protected function validate()
  777. {
  778. return $this->listener->getStrategy($this->_em, $this->getClassMetadata()->name)->getName() === Strategy::NESTED;
  779. }
  780. /**
  781. * Collect errors on given tree if
  782. * where are any
  783. *
  784. * @param array $errors
  785. * @param object $root
  786. * @return void
  787. */
  788. private function verifyTree(&$errors, $root = null)
  789. {
  790. $meta = $this->getClassMetadata();
  791. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  792. $identifier = $meta->getSingleIdentifierFieldName();
  793. $rootId = isset($config['root']) ? $meta->getReflectionProperty($config['root'])->getValue($root) : null;
  794. $qb = $this->_em->createQueryBuilder();
  795. $qb->select($qb->expr()->min('node.'.$config['left']))
  796. ->from($config['useObjectClass'], 'node')
  797. ;
  798. if (isset($config['root'])) {
  799. $qb->where($rootId === null ?
  800. $qb->expr()->isNull('node.'.$config['root']) :
  801. $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
  802. );
  803. }
  804. $min = intval($qb->getQuery()->getSingleScalarResult());
  805. $edge = $this->listener->getStrategy($this->_em, $meta->name)->max($this->_em, $config['useObjectClass'], $rootId);
  806. // check duplicate right and left values
  807. for ($i = $min; $i <= $edge; $i++) {
  808. $qb = $this->_em->createQueryBuilder();
  809. $qb->select($qb->expr()->count('node.'.$identifier))
  810. ->from($config['useObjectClass'], 'node')
  811. ->where($qb->expr()->orX(
  812. $qb->expr()->eq('node.'.$config['left'], $i),
  813. $qb->expr()->eq('node.'.$config['right'], $i)
  814. ))
  815. ;
  816. if (isset($config['root'])) {
  817. $qb->andWhere($rootId === null ?
  818. $qb->expr()->isNull('node.'.$config['root']) :
  819. $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
  820. );
  821. }
  822. $count = intval($qb->getQuery()->getSingleScalarResult());
  823. if ($count !== 1) {
  824. if ($count === 0) {
  825. $errors[] = "index [{$i}], missing" . ($root ? ' on tree root: ' . $rootId : '');
  826. } else {
  827. $errors[] = "index [{$i}], duplicate" . ($root ? ' on tree root: ' . $rootId : '');
  828. }
  829. }
  830. }
  831. // check for missing parents
  832. $qb = $this->_em->createQueryBuilder();
  833. $qb->select('node')
  834. ->from($config['useObjectClass'], 'node')
  835. ->leftJoin('node.'.$config['parent'], 'parent')
  836. ->where($qb->expr()->isNotNull('node.'.$config['parent']))
  837. ->andWhere($qb->expr()->isNull('parent.'.$identifier))
  838. ;
  839. if (isset($config['root'])) {
  840. $qb->andWhere($rootId === null ?
  841. $qb->expr()->isNull('node.'.$config['root']) :
  842. $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
  843. );
  844. }
  845. $nodes = $qb->getQuery()->getArrayResult();
  846. if (count($nodes)) {
  847. foreach ($nodes as $node) {
  848. $errors[] = "node [{$node[$identifier]}] has missing parent" . ($root ? ' on tree root: ' . $rootId : '');
  849. }
  850. return; // loading broken relation can cause infinite loop
  851. }
  852. $qb = $this->_em->createQueryBuilder();
  853. $qb->select('node')
  854. ->from($config['useObjectClass'], 'node')
  855. ->where($qb->expr()->lt('node.'.$config['right'], 'node.'.$config['left']))
  856. ;
  857. if (isset($config['root'])) {
  858. $qb->andWhere($rootId === null ?
  859. $qb->expr()->isNull('node.'.$config['root']) :
  860. $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
  861. );
  862. }
  863. $result = $qb->getQuery()
  864. ->setMaxResults(1)
  865. ->getResult(Query::HYDRATE_ARRAY);
  866. $node = count($result) ? array_shift($result) : null;
  867. if ($node) {
  868. $id = $node[$identifier];
  869. $errors[] = "node [{$id}], left is greater than right" . ($root ? ' on tree root: ' . $rootId : '');
  870. }
  871. $qb = $this->_em->createQueryBuilder();
  872. $qb->select('node')
  873. ->from($config['useObjectClass'], 'node')
  874. ;
  875. if (isset($config['root'])) {
  876. $qb->where($rootId === null ?
  877. $qb->expr()->isNull('node.'.$config['root']) :
  878. $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
  879. );
  880. }
  881. $nodes = $qb->getQuery()->getResult(Query::HYDRATE_OBJECT);
  882. foreach ($nodes as $node) {
  883. $right = $meta->getReflectionProperty($config['right'])->getValue($node);
  884. $left = $meta->getReflectionProperty($config['left'])->getValue($node);
  885. $id = $meta->getReflectionProperty($identifier)->getValue($node);
  886. $parent = $meta->getReflectionProperty($config['parent'])->getValue($node);
  887. if (!$right || !$left) {
  888. $errors[] = "node [{$id}] has invalid left or right values";
  889. } elseif ($right == $left) {
  890. $errors[] = "node [{$id}] has identical left and right values";
  891. } elseif ($parent) {
  892. if ($parent instanceof Proxy && !$parent->__isInitialized__) {
  893. $this->_em->refresh($parent);
  894. }
  895. $parentRight = $meta->getReflectionProperty($config['right'])->getValue($parent);
  896. $parentLeft = $meta->getReflectionProperty($config['left'])->getValue($parent);
  897. $parentId = $meta->getReflectionProperty($identifier)->getValue($parent);
  898. if ($left < $parentLeft) {
  899. $errors[] = "node [{$id}] left is less than parent`s [{$parentId}] left value";
  900. } elseif ($right > $parentRight) {
  901. $errors[] = "node [{$id}] right is greater than parent`s [{$parentId}] right value";
  902. }
  903. } else {
  904. $qb = $this->_em->createQueryBuilder();
  905. $qb->select($qb->expr()->count('node.'.$identifier))
  906. ->from($config['useObjectClass'], 'node')
  907. ->where($qb->expr()->lt('node.'.$config['left'], $left))
  908. ->andWhere($qb->expr()->gt('node.'.$config['right'], $right))
  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. if ($count = intval($qb->getQuery()->getSingleScalarResult())) {
  917. $errors[] = "node [{$id}] parent field is blank, but it has a parent";
  918. }
  919. }
  920. }
  921. }
  922. /**
  923. * Removes single node without touching children
  924. *
  925. * @internal
  926. * @param EntityWrapper $wrapped
  927. * @return void
  928. */
  929. private function removeSingle(EntityWrapper $wrapped)
  930. {
  931. $meta = $this->getClassMetadata();
  932. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  933. $pk = $meta->getSingleIdentifierFieldName();
  934. $nodeId = $wrapped->getIdentifier();
  935. // prevent from deleting whole branch
  936. $qb = $this->_em->createQueryBuilder();
  937. $qb->update($config['useObjectClass'], 'node')
  938. ->set('node.'.$config['left'], 0)
  939. ->set('node.'.$config['right'], 0)
  940. ->where($nodeId === null ?
  941. $qb->expr()->isNull('node.'.$pk) :
  942. $qb->expr()->eq('node.'.$pk, is_string($nodeId) ? $qb->expr()->literal($nodeId) : $nodeId)
  943. )
  944. ;
  945. $qb->getQuery()->getSingleScalarResult();
  946. // remove the node from database
  947. $qb = $this->_em->createQueryBuilder();
  948. $qb->delete($config['useObjectClass'], 'node')
  949. ->where($nodeId === null ?
  950. $qb->expr()->isNull('node.'.$pk) :
  951. $qb->expr()->eq('node.'.$pk, is_string($nodeId) ? $qb->expr()->literal($nodeId) : $nodeId)
  952. )
  953. ;
  954. $qb->getQuery()->getSingleScalarResult();
  955. // remove from identity map
  956. $this->_em->getUnitOfWork()->removeFromIdentityMap($wrapped->getObject());
  957. }
  958. }