NestedTreeRepository.php 42 KB

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