NestedTreeRepository.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  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. $qb->orderBy('node.' . $config['left'], 'ASC');
  308. } else {
  309. if ($meta->hasField($sortByField) && in_array(strtolower($direction), array('asc', 'desc'))) {
  310. $qb->orderBy('node.' . $sortByField, $direction);
  311. } else {
  312. throw new InvalidArgumentException("Invalid sort options specified: field - {$sortByField}, direction - {$direction}");
  313. }
  314. }
  315. return $qb;
  316. }
  317. /**
  318. * Get tree leafs query
  319. *
  320. * @param object $root - root node in case of root tree is required
  321. * @param string $sortByField - field name to sort by
  322. * @param string $direction - sort direction : "ASC" or "DESC"
  323. * @return Doctrine\ORM\Query
  324. */
  325. public function getLeafsQuery($root = null, $sortByField = null, $direction = 'ASC')
  326. {
  327. return $this->getLeafsQueryBuilder($root, $sortByField, $direction)->getQuery();
  328. }
  329. /**
  330. * Get list of leaf nodes of the tree
  331. *
  332. * @param object $root - root node in case of root tree is required
  333. * @param string $sortByField - field name to sort by
  334. * @param string $direction - sort direction : "ASC" or "DESC"
  335. * @return array
  336. */
  337. public function getLeafs($root = null, $sortByField = null, $direction = 'ASC')
  338. {
  339. return $this->getLeafsQuery($root, $sortByField, $direction)->getResult();
  340. }
  341. /**
  342. * Get the query builder for next siblings of the given $node
  343. *
  344. * @param object $node
  345. * @param bool $includeSelf - include the node itself
  346. * @throws \Gedmo\Exception\InvalidArgumentException - if input is invalid
  347. * @return Doctrine\ORM\QueryBuilder
  348. */
  349. public function getNextSiblingsQueryBuilder($node, $includeSelf = false)
  350. {
  351. $meta = $this->getClassMetadata();
  352. if (!$node instanceof $meta->name) {
  353. throw new InvalidArgumentException("Node is not related to this repository");
  354. }
  355. $wrapped = new EntityWrapper($node, $this->_em);
  356. if (!$wrapped->hasValidIdentifier()) {
  357. throw new InvalidArgumentException("Node is not managed by UnitOfWork");
  358. }
  359. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  360. $parent = $wrapped->getPropertyValue($config['parent']);
  361. if (isset($config['root']) && !$parent) {
  362. throw new InvalidArgumentException("Cannot get siblings from tree root node");
  363. }
  364. $left = $wrapped->getPropertyValue($config['left']);
  365. $qb = $this->_em->createQueryBuilder();
  366. $qb->select('node')
  367. ->from($config['useObjectClass'], 'node')
  368. ->where($includeSelf ?
  369. $qb->expr()->gte('node.'.$config['left'], $left) :
  370. $qb->expr()->gt('node.'.$config['left'], $left)
  371. )
  372. ->orderBy("node.{$config['left']}", 'ASC')
  373. ;
  374. if ($parent) {
  375. $wrappedParent = new EntityWrapper($parent, $this->_em);
  376. $parentId = $wrappedParent->getIdentifier();
  377. $qb->andWhere($qb->expr()->eq('node.'.$config['parent'], is_string($parentId) ? $qb->expr()->literal($parentId) : $parentId));
  378. } else {
  379. $qb->andWhere($qb->expr()->isNull('node.'.$config['parent']));
  380. }
  381. return $qb;
  382. }
  383. /**
  384. * Get the query for next siblings of the given $node
  385. *
  386. * @param object $node
  387. * @param bool $includeSelf - include the node itself
  388. * @return Doctrine\ORM\Query
  389. */
  390. public function getNextSiblingsQuery($node, $includeSelf = false)
  391. {
  392. return $this->getNextSiblingsQueryBuilder($node, $includeSelf)->getQuery();
  393. }
  394. /**
  395. * Find the next siblings of the given $node
  396. *
  397. * @param object $node
  398. * @param bool $includeSelf - include the node itself
  399. * @return array
  400. */
  401. public function getNextSiblings($node, $includeSelf = false)
  402. {
  403. return $this->getNextSiblingsQuery($node, $includeSelf)->getResult();
  404. }
  405. /**
  406. * Get query builder for previous siblings of the given $node
  407. *
  408. * @param object $node
  409. * @param bool $includeSelf - include the node itself
  410. * @throws \Gedmo\Exception\InvalidArgumentException - if input is invalid
  411. * @return Doctrine\ORM\QueryBuilder
  412. */
  413. public function getPrevSiblingsQueryBuilder($node, $includeSelf = false)
  414. {
  415. $meta = $this->getClassMetadata();
  416. if (!$node instanceof $meta->name) {
  417. throw new InvalidArgumentException("Node is not related to this repository");
  418. }
  419. $wrapped = new EntityWrapper($node, $this->_em);
  420. if (!$wrapped->hasValidIdentifier()) {
  421. throw new InvalidArgumentException("Node is not managed by UnitOfWork");
  422. }
  423. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  424. $parent = $wrapped->getPropertyValue($config['parent']);
  425. if (isset($config['root']) && !$parent) {
  426. throw new InvalidArgumentException("Cannot get siblings from tree root node");
  427. }
  428. $left = $wrapped->getPropertyValue($config['left']);
  429. $qb = $this->_em->createQueryBuilder();
  430. $qb->select('node')
  431. ->from($config['useObjectClass'], 'node')
  432. ->where($includeSelf ?
  433. $qb->expr()->lte('node.'.$config['left'], $left) :
  434. $qb->expr()->lt('node.'.$config['left'], $left)
  435. )
  436. ->orderBy("node.{$config['left']}", 'ASC')
  437. ;
  438. if ($parent) {
  439. $wrappedParent = new EntityWrapper($parent, $this->_em);
  440. $parentId = $wrappedParent->getIdentifier();
  441. $qb->andWhere($qb->expr()->eq('node.'.$config['parent'], is_string($parentId) ? $qb->expr()->literal($parentId) : $parentId));
  442. } else {
  443. $qb->andWhere($qb->expr()->isNull('node.'.$config['parent']));
  444. }
  445. return $qb;
  446. }
  447. /**
  448. * Get query for previous siblings of the given $node
  449. *
  450. * @param object $node
  451. * @param bool $includeSelf - include the node itself
  452. * @throws \Gedmo\Exception\InvalidArgumentException - if input is invalid
  453. * @return Doctrine\ORM\Query
  454. */
  455. public function getPrevSiblingsQuery($node, $includeSelf = false)
  456. {
  457. return $this->getPrevSiblingsQueryBuilder($node, $includeSelf)->getQuery();
  458. }
  459. /**
  460. * Find the previous siblings of the given $node
  461. *
  462. * @param object $node
  463. * @param bool $includeSelf - include the node itself
  464. * @return array
  465. */
  466. public function getPrevSiblings($node, $includeSelf = false)
  467. {
  468. return $this->getPrevSiblingsQuery($node, $includeSelf)->getResult();
  469. }
  470. /**
  471. * Move the node down in the same level
  472. *
  473. * @param object $node
  474. * @param mixed $number
  475. * integer - number of positions to shift
  476. * boolean - if "true" - shift till last position
  477. * @throws RuntimeException - if something fails in transaction
  478. * @return boolean - true if shifted
  479. */
  480. public function moveDown($node, $number = 1)
  481. {
  482. $result = false;
  483. $meta = $this->getClassMetadata();
  484. if ($node instanceof $meta->name) {
  485. $nextSiblings = $this->getNextSiblings($node);
  486. if ($numSiblings = count($nextSiblings)) {
  487. $result = true;
  488. if ($number === true) {
  489. $number = $numSiblings;
  490. } elseif ($number > $numSiblings) {
  491. $number = $numSiblings;
  492. }
  493. $this->listener
  494. ->getStrategy($this->_em, $meta->name)
  495. ->updateNode($this->_em, $node, $nextSiblings[$number - 1], Nested::NEXT_SIBLING);
  496. }
  497. } else {
  498. throw new InvalidArgumentException("Node is not related to this repository");
  499. }
  500. return $result;
  501. }
  502. /**
  503. * Move the node up in the same level
  504. *
  505. * @param object $node
  506. * @param mixed $number
  507. * integer - number of positions to shift
  508. * boolean - true shift till first position
  509. * @throws RuntimeException - if something fails in transaction
  510. * @return boolean - true if shifted
  511. */
  512. public function moveUp($node, $number = 1)
  513. {
  514. $result = false;
  515. $meta = $this->getClassMetadata();
  516. if ($node instanceof $meta->name) {
  517. $prevSiblings = array_reverse($this->getPrevSiblings($node));
  518. if ($numSiblings = count($prevSiblings)) {
  519. $result = true;
  520. if ($number === true) {
  521. $number = $numSiblings;
  522. } elseif ($number > $numSiblings) {
  523. $number = $numSiblings;
  524. }
  525. $this->listener
  526. ->getStrategy($this->_em, $meta->name)
  527. ->updateNode($this->_em, $node, $prevSiblings[$number - 1], Nested::PREV_SIBLING);
  528. }
  529. } else {
  530. throw new InvalidArgumentException("Node is not related to this repository");
  531. }
  532. return $result;
  533. }
  534. /**
  535. * UNSAFE: be sure to backup before runing this method when necessary
  536. *
  537. * Removes given $node from the tree and reparents its descendants
  538. *
  539. * @param object $node
  540. * @throws RuntimeException - if something fails in transaction
  541. * @return void
  542. */
  543. public function removeFromTree($node)
  544. {
  545. $meta = $this->getClassMetadata();
  546. if ($node instanceof $meta->name) {
  547. $wrapped = new EntityWrapper($node, $this->_em);
  548. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  549. $right = $wrapped->getPropertyValue($config['right']);
  550. $left = $wrapped->getPropertyValue($config['left']);
  551. $rootId = isset($config['root']) ? $wrapped->getPropertyValue($config['root']) : null;
  552. if ($right == $left + 1) {
  553. $this->removeSingle($wrapped);
  554. $this->listener
  555. ->getStrategy($this->_em, $meta->name)
  556. ->shiftRL($this->_em, $config['useObjectClass'], $right, -2, $rootId);
  557. return; // node was a leaf
  558. }
  559. // process updates in transaction
  560. $this->_em->getConnection()->beginTransaction();
  561. try {
  562. $parent = $wrapped->getPropertyValue($config['parent']);
  563. $parentId = null;
  564. if ($parent) {
  565. $wrappedParrent = new EntityWrapper($parent, $this->_em);
  566. $parentId = $wrappedParrent->getIdentifier();
  567. }
  568. $pk = $meta->getSingleIdentifierFieldName();
  569. $nodeId = $wrapped->getIdentifier();
  570. $shift = -1;
  571. // in case if root node is removed, childs become roots
  572. if (isset($config['root']) && !$parent) {
  573. $qb = $this->_em->createQueryBuilder();
  574. $qb->select('node.'.$pk, 'node.'.$config['left'], 'node.'.$config['right'])
  575. ->from($config['useObjectClass'], 'node')
  576. ->where($nodeId === null ?
  577. $qb->expr()->isNull('node.'.$config['parent']) :
  578. $qb->expr()->eq('node.'.$config['parent'], is_string($nodeId) ? $qb->expr()->literal($nodeId) : $nodeId)
  579. )
  580. ;
  581. $nodes = $qb->getQuery()->getArrayResult();
  582. foreach ($nodes as $newRoot) {
  583. $left = $newRoot[$config['left']];
  584. $right = $newRoot[$config['right']];
  585. $rootId = $newRoot[$pk];
  586. $shift = -($left - 1);
  587. $qb = $this->_em->createQueryBuilder();
  588. $qb->update($config['useObjectClass'], 'node')
  589. ->set('node.'.$config['root'], $rootId === null ?
  590. 'NULL' :
  591. (is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
  592. )
  593. ->where($qb->expr()->eq('node.'.$config['root'], is_string($nodeId) ? $qb->expr()->literal($nodeId) : $nodeId))
  594. ->andWhere($qb->expr()->gte('node.'.$config['left'], $left))
  595. ->andWhere($qb->expr()->lte('node.'.$config['right'], $right))
  596. ;
  597. $qb->getQuery()->getSingleScalarResult();
  598. $qb = $this->_em->createQueryBuilder();
  599. $qb->update($config['useObjectClass'], 'node')
  600. ->set('node.'.$config['parent'], $parentId === null ?
  601. 'NULL' :
  602. (is_string($parentId) ? $qb->expr()->literal($parentId) : $parentId)
  603. )
  604. ->where($nodeId === null ?
  605. $qb->expr()->isNull('node.'.$config['parent']) :
  606. $qb->expr()->eq('node.'.$config['parent'], is_string($nodeId) ? $qb->expr()->literal($nodeId) : $nodeId)
  607. )
  608. ->andWhere($rootId === null ?
  609. $qb->expr()->isNull('node.'.$config['root']) :
  610. $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
  611. )
  612. ;
  613. $qb->getQuery()->getSingleScalarResult();
  614. $this->listener
  615. ->getStrategy($this->_em, $meta->name)
  616. ->shiftRangeRL($this->_em, $config['useObjectClass'], $left, $right, $shift, $rootId, $rootId, - 1);
  617. $this->listener
  618. ->getStrategy($this->_em, $meta->name)
  619. ->shiftRL($this->_em, $config['useObjectClass'], $right, -2, $rootId);
  620. }
  621. } else {
  622. $qb = $this->_em->createQueryBuilder();
  623. $qb->update($config['useObjectClass'], 'node')
  624. ->set('node.'.$config['parent'], null === $parentId ?
  625. 'NULL' :
  626. (is_string($parentId) ? $qb->expr()->literal($parentId) : $parentId)
  627. )
  628. ->where($nodeId === null ?
  629. $qb->expr()->isNull('node.'.$config['parent']) :
  630. $qb->expr()->eq('node.'.$config['parent'], is_string($nodeId) ? $qb->expr()->literal($nodeId) : $nodeId)
  631. )
  632. ;
  633. if (isset($config['root'])) {
  634. $qb->andWhere($rootId === null ?
  635. $qb->expr()->isNull('node.'.$config['root']) :
  636. $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
  637. );
  638. }
  639. $qb->getQuery()->getSingleScalarResult();
  640. $this->listener
  641. ->getStrategy($this->_em, $meta->name)
  642. ->shiftRangeRL($this->_em, $config['useObjectClass'], $left, $right, $shift, $rootId, $rootId, - 1);
  643. $this->listener
  644. ->getStrategy($this->_em, $meta->name)
  645. ->shiftRL($this->_em, $config['useObjectClass'], $right, -2, $rootId);
  646. }
  647. $this->removeSingle($wrapped);
  648. $this->_em->getConnection()->commit();
  649. } catch (\Exception $e) {
  650. $this->_em->close();
  651. $this->_em->getConnection()->rollback();
  652. die($e->getMessage());
  653. throw new \Gedmo\Exception\RuntimeException('Transaction failed', null, $e);
  654. }
  655. } else {
  656. throw new InvalidArgumentException("Node is not related to this repository");
  657. }
  658. }
  659. /**
  660. * Reorders the sibling nodes and child nodes by given $node,
  661. * according to the $sortByField and $direction specified
  662. *
  663. * @param object $node - from which node to start reordering the tree
  664. * @param string $sortByField - field name to sort by
  665. * @param string $direction - sort direction : "ASC" or "DESC"
  666. * @param boolean $verify - true to verify tree first
  667. * @return void
  668. */
  669. public function reorder($node, $sortByField = null, $direction = 'ASC', $verify = true)
  670. {
  671. $meta = $this->getClassMetadata();
  672. if ($node instanceof $meta->name) {
  673. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  674. if ($verify && is_array($this->verify())) {
  675. return false;
  676. }
  677. $nodes = $this->children($node, true, $sortByField, $direction);
  678. foreach ($nodes as $node) {
  679. $wrapped = new EntityWrapper($node, $this->_em);
  680. $right = $wrapped->getPropertyValue($config['right']);
  681. $left = $wrapped->getPropertyValue($config['left']);
  682. $this->moveDown($node, true);
  683. if ($left != ($right - 1)) {
  684. $this->reorder($node, $sortByField, $direction, false);
  685. }
  686. }
  687. } else {
  688. throw new InvalidArgumentException("Node is not related to this repository");
  689. }
  690. }
  691. /**
  692. * Verifies that current tree is valid.
  693. * If any error is detected it will return an array
  694. * with a list of errors found on tree
  695. *
  696. * @return mixed
  697. * boolean - true on success
  698. * array - error list on failure
  699. */
  700. public function verify()
  701. {
  702. if (!$this->childCount()) {
  703. return true; // tree is empty
  704. }
  705. $errors = array();
  706. $meta = $this->getClassMetadata();
  707. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  708. if (isset($config['root'])) {
  709. $trees = $this->getRootNodes();
  710. foreach ($trees as $tree) {
  711. $this->verifyTree($errors, $tree);
  712. }
  713. } else {
  714. $this->verifyTree($errors);
  715. }
  716. return $errors ?: true;
  717. }
  718. /**
  719. * Tries to recover the tree
  720. *
  721. * @todo implement
  722. * @throws RuntimeException - if something fails in transaction
  723. * @return void
  724. */
  725. public function recover()
  726. {
  727. if ($this->verify() === true) {
  728. return;
  729. }
  730. // not yet implemented
  731. }
  732. /**
  733. * {@inheritDoc}
  734. */
  735. public function getNodesHierarchyQueryBuilder($node = null, $direct, array $config, array $options = array(), $includeNode = false)
  736. {
  737. return $this->childrenQueryBuilder(
  738. $node,
  739. $direct,
  740. isset($config['root']) ? array($config['root'], $config['left']) : $config['left'],
  741. 'ASC',
  742. $includeNode
  743. );
  744. }
  745. /**
  746. * {@inheritDoc}
  747. */
  748. public function getNodesHierarchyQuery($node = null, $direct, array $config, array $options = array(), $includeNode = false)
  749. {
  750. return $this->getNodesHierarchyQueryBuilder($node, $direct, $config, $options)->getQuery();
  751. }
  752. /**
  753. * {@inheritdoc}
  754. */
  755. public function getNodesHierarchy($node = null, $direct, array $config, array $options = array(), $includeNode = false)
  756. {
  757. return $this->getNodesHierarchyQuery($node, $direct, $config, $options)->getArrayResult();
  758. }
  759. /**
  760. * {@inheritdoc}
  761. */
  762. protected function validate()
  763. {
  764. return $this->listener->getStrategy($this->_em, $this->getClassMetadata()->name)->getName() === Strategy::NESTED;
  765. }
  766. /**
  767. * Collect errors on given tree if
  768. * where are any
  769. *
  770. * @param array $errors
  771. * @param object $root
  772. * @return void
  773. */
  774. private function verifyTree(&$errors, $root = null)
  775. {
  776. $meta = $this->getClassMetadata();
  777. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  778. $identifier = $meta->getSingleIdentifierFieldName();
  779. $rootId = isset($config['root']) ? $meta->getReflectionProperty($config['root'])->getValue($root) : null;
  780. $qb = $this->_em->createQueryBuilder();
  781. $qb->select($qb->expr()->min('node.'.$config['left']))
  782. ->from($config['useObjectClass'], 'node')
  783. ;
  784. if (isset($config['root'])) {
  785. $qb->where($rootId === null ?
  786. $qb->expr()->isNull('node.'.$config['root']) :
  787. $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
  788. );
  789. }
  790. $min = intval($qb->getQuery()->getSingleScalarResult());
  791. $edge = $this->listener->getStrategy($this->_em, $meta->name)->max($this->_em, $config['useObjectClass'], $rootId);
  792. // check duplicate right and left values
  793. for ($i = $min; $i <= $edge; $i++) {
  794. $qb = $this->_em->createQueryBuilder();
  795. $qb->select($qb->expr()->count('node.'.$identifier))
  796. ->from($config['useObjectClass'], 'node')
  797. ->where($qb->expr()->orX(
  798. $qb->expr()->eq('node.'.$config['left'], $i),
  799. $qb->expr()->eq('node.'.$config['right'], $i)
  800. ))
  801. ;
  802. if (isset($config['root'])) {
  803. $qb->andWhere($rootId === null ?
  804. $qb->expr()->isNull('node.'.$config['root']) :
  805. $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
  806. );
  807. }
  808. $count = intval($qb->getQuery()->getSingleScalarResult());
  809. if ($count !== 1) {
  810. if ($count === 0) {
  811. $errors[] = "index [{$i}], missing" . ($root ? ' on tree root: ' . $rootId : '');
  812. } else {
  813. $errors[] = "index [{$i}], duplicate" . ($root ? ' on tree root: ' . $rootId : '');
  814. }
  815. }
  816. }
  817. // check for missing parents
  818. $qb = $this->_em->createQueryBuilder();
  819. $qb->select('node')
  820. ->from($config['useObjectClass'], 'node')
  821. ->leftJoin('node.'.$config['parent'], 'parent')
  822. ->where($qb->expr()->isNotNull('node.'.$config['parent']))
  823. ->andWhere($qb->expr()->isNull('parent.'.$identifier))
  824. ;
  825. if (isset($config['root'])) {
  826. $qb->andWhere($rootId === null ?
  827. $qb->expr()->isNull('node.'.$config['root']) :
  828. $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
  829. );
  830. }
  831. $nodes = $qb->getQuery()->getArrayResult();
  832. if (count($nodes)) {
  833. foreach ($nodes as $node) {
  834. $errors[] = "node [{$node[$identifier]}] has missing parent" . ($root ? ' on tree root: ' . $rootId : '');
  835. }
  836. return; // loading broken relation can cause infinite loop
  837. }
  838. $qb = $this->_em->createQueryBuilder();
  839. $qb->select('node')
  840. ->from($config['useObjectClass'], 'node')
  841. ->where($qb->expr()->lt('node.'.$config['right'], 'node.'.$config['left']))
  842. ;
  843. if (isset($config['root'])) {
  844. $qb->andWhere($rootId === null ?
  845. $qb->expr()->isNull('node.'.$config['root']) :
  846. $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
  847. );
  848. }
  849. $result = $qb->getQuery()
  850. ->setMaxResults(1)
  851. ->getResult(Query::HYDRATE_ARRAY);
  852. $node = count($result) ? array_shift($result) : null;
  853. if ($node) {
  854. $id = $node[$identifier];
  855. $errors[] = "node [{$id}], left is greater than right" . ($root ? ' on tree root: ' . $rootId : '');
  856. }
  857. $qb = $this->_em->createQueryBuilder();
  858. $qb->select('node')
  859. ->from($config['useObjectClass'], 'node')
  860. ;
  861. if (isset($config['root'])) {
  862. $qb->where($rootId === null ?
  863. $qb->expr()->isNull('node.'.$config['root']) :
  864. $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
  865. );
  866. }
  867. $nodes = $qb->getQuery()->getResult(Query::HYDRATE_OBJECT);
  868. foreach ($nodes as $node) {
  869. $right = $meta->getReflectionProperty($config['right'])->getValue($node);
  870. $left = $meta->getReflectionProperty($config['left'])->getValue($node);
  871. $id = $meta->getReflectionProperty($identifier)->getValue($node);
  872. $parent = $meta->getReflectionProperty($config['parent'])->getValue($node);
  873. if (!$right || !$left) {
  874. $errors[] = "node [{$id}] has invalid left or right values";
  875. } elseif ($right == $left) {
  876. $errors[] = "node [{$id}] has identical left and right values";
  877. } elseif ($parent) {
  878. if ($parent instanceof Proxy && !$parent->__isInitialized__) {
  879. $this->_em->refresh($parent);
  880. }
  881. $parentRight = $meta->getReflectionProperty($config['right'])->getValue($parent);
  882. $parentLeft = $meta->getReflectionProperty($config['left'])->getValue($parent);
  883. $parentId = $meta->getReflectionProperty($identifier)->getValue($parent);
  884. if ($left < $parentLeft) {
  885. $errors[] = "node [{$id}] left is less than parent`s [{$parentId}] left value";
  886. } elseif ($right > $parentRight) {
  887. $errors[] = "node [{$id}] right is greater than parent`s [{$parentId}] right value";
  888. }
  889. } else {
  890. $qb = $this->_em->createQueryBuilder();
  891. $qb->select($qb->expr()->count('node.'.$identifier))
  892. ->from($config['useObjectClass'], 'node')
  893. ->where($qb->expr()->lt('node.'.$config['left'], $left))
  894. ->andWhere($qb->expr()->gt('node.'.$config['right'], $right))
  895. ;
  896. if (isset($config['root'])) {
  897. $qb->andWhere($rootId === null ?
  898. $qb->expr()->isNull('node.'.$config['root']) :
  899. $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
  900. );
  901. }
  902. if ($count = intval($qb->getQuery()->getSingleScalarResult())) {
  903. $errors[] = "node [{$id}] parent field is blank, but it has a parent";
  904. }
  905. }
  906. }
  907. }
  908. /**
  909. * Removes single node without touching children
  910. *
  911. * @internal
  912. * @param EntityWrapper $wrapped
  913. * @return void
  914. */
  915. private function removeSingle(EntityWrapper $wrapped)
  916. {
  917. $meta = $this->getClassMetadata();
  918. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  919. $pk = $meta->getSingleIdentifierFieldName();
  920. $nodeId = $wrapped->getIdentifier();
  921. // prevent from deleting whole branch
  922. $qb = $this->_em->createQueryBuilder();
  923. $qb->update($config['useObjectClass'], 'node')
  924. ->set('node.'.$config['left'], 0)
  925. ->set('node.'.$config['right'], 0)
  926. ->where($nodeId === null ?
  927. $qb->expr()->isNull('node.'.$pk) :
  928. $qb->expr()->eq('node.'.$pk, is_string($nodeId) ? $qb->expr()->literal($nodeId) : $nodeId)
  929. )
  930. ;
  931. $qb->getQuery()->getSingleScalarResult();
  932. // remove the node from database
  933. $qb = $this->_em->createQueryBuilder();
  934. $qb->delete($config['useObjectClass'], 'node')
  935. ->where($nodeId === null ?
  936. $qb->expr()->isNull('node.'.$pk) :
  937. $qb->expr()->eq('node.'.$pk, is_string($nodeId) ? $qb->expr()->literal($nodeId) : $nodeId)
  938. )
  939. ;
  940. $qb->getQuery()->getSingleScalarResult();
  941. // remove from identity map
  942. $this->_em->getUnitOfWork()->removeFromIdentityMap($wrapped->getObject());
  943. }
  944. }