NestedTreeRepository.php 40 KB

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