NestedTreeRepository.php 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  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 = false, array $options = array(), $includeNode = false)
  739. {
  740. $meta = $this->getClassMetadata();
  741. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  742. return $this->childrenQueryBuilder(
  743. $node,
  744. $direct,
  745. isset($config['root']) ? array($config['root'], $config['left']) : $config['left'],
  746. 'ASC',
  747. $includeNode
  748. );
  749. }
  750. /**
  751. * {@inheritDoc}
  752. */
  753. public function getNodesHierarchyQuery($node = null, $direct = false, array $options = array(), $includeNode = false)
  754. {
  755. return $this->getNodesHierarchyQueryBuilder($node, $direct, $options, $includeNode)->getQuery();
  756. }
  757. /**
  758. * {@inheritdoc}
  759. */
  760. public function getNodesHierarchy($node = null, $direct = false, array $options = array(), $includeNode = false)
  761. {
  762. return $this->getNodesHierarchyQuery($node, $direct, $options, $includeNode)->getArrayResult();
  763. }
  764. /**
  765. * {@inheritdoc}
  766. */
  767. protected function validate()
  768. {
  769. return $this->listener->getStrategy($this->_em, $this->getClassMetadata()->name)->getName() === Strategy::NESTED;
  770. }
  771. /**
  772. * Collect errors on given tree if
  773. * where are any
  774. *
  775. * @param array $errors
  776. * @param object $root
  777. * @return void
  778. */
  779. private function verifyTree(&$errors, $root = null)
  780. {
  781. $meta = $this->getClassMetadata();
  782. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  783. $identifier = $meta->getSingleIdentifierFieldName();
  784. $rootId = isset($config['root']) ? $meta->getReflectionProperty($config['root'])->getValue($root) : null;
  785. $qb = $this->_em->createQueryBuilder();
  786. $qb->select($qb->expr()->min('node.'.$config['left']))
  787. ->from($config['useObjectClass'], 'node')
  788. ;
  789. if (isset($config['root'])) {
  790. $qb->where($rootId === null ?
  791. $qb->expr()->isNull('node.'.$config['root']) :
  792. $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
  793. );
  794. }
  795. $min = intval($qb->getQuery()->getSingleScalarResult());
  796. $edge = $this->listener->getStrategy($this->_em, $meta->name)->max($this->_em, $config['useObjectClass'], $rootId);
  797. // check duplicate right and left values
  798. for ($i = $min; $i <= $edge; $i++) {
  799. $qb = $this->_em->createQueryBuilder();
  800. $qb->select($qb->expr()->count('node.'.$identifier))
  801. ->from($config['useObjectClass'], 'node')
  802. ->where($qb->expr()->orX(
  803. $qb->expr()->eq('node.'.$config['left'], $i),
  804. $qb->expr()->eq('node.'.$config['right'], $i)
  805. ))
  806. ;
  807. if (isset($config['root'])) {
  808. $qb->andWhere($rootId === null ?
  809. $qb->expr()->isNull('node.'.$config['root']) :
  810. $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
  811. );
  812. }
  813. $count = intval($qb->getQuery()->getSingleScalarResult());
  814. if ($count !== 1) {
  815. if ($count === 0) {
  816. $errors[] = "index [{$i}], missing" . ($root ? ' on tree root: ' . $rootId : '');
  817. } else {
  818. $errors[] = "index [{$i}], duplicate" . ($root ? ' on tree root: ' . $rootId : '');
  819. }
  820. }
  821. }
  822. // check for missing parents
  823. $qb = $this->_em->createQueryBuilder();
  824. $qb->select('node')
  825. ->from($config['useObjectClass'], 'node')
  826. ->leftJoin('node.'.$config['parent'], 'parent')
  827. ->where($qb->expr()->isNotNull('node.'.$config['parent']))
  828. ->andWhere($qb->expr()->isNull('parent.'.$identifier))
  829. ;
  830. if (isset($config['root'])) {
  831. $qb->andWhere($rootId === null ?
  832. $qb->expr()->isNull('node.'.$config['root']) :
  833. $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
  834. );
  835. }
  836. $nodes = $qb->getQuery()->getArrayResult();
  837. if (count($nodes)) {
  838. foreach ($nodes as $node) {
  839. $errors[] = "node [{$node[$identifier]}] has missing parent" . ($root ? ' on tree root: ' . $rootId : '');
  840. }
  841. return; // loading broken relation can cause infinite loop
  842. }
  843. $qb = $this->_em->createQueryBuilder();
  844. $qb->select('node')
  845. ->from($config['useObjectClass'], 'node')
  846. ->where($qb->expr()->lt('node.'.$config['right'], 'node.'.$config['left']))
  847. ;
  848. if (isset($config['root'])) {
  849. $qb->andWhere($rootId === null ?
  850. $qb->expr()->isNull('node.'.$config['root']) :
  851. $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
  852. );
  853. }
  854. $result = $qb->getQuery()
  855. ->setMaxResults(1)
  856. ->getResult(Query::HYDRATE_ARRAY);
  857. $node = count($result) ? array_shift($result) : null;
  858. if ($node) {
  859. $id = $node[$identifier];
  860. $errors[] = "node [{$id}], left is greater than right" . ($root ? ' on tree root: ' . $rootId : '');
  861. }
  862. $qb = $this->_em->createQueryBuilder();
  863. $qb->select('node')
  864. ->from($config['useObjectClass'], 'node')
  865. ;
  866. if (isset($config['root'])) {
  867. $qb->where($rootId === null ?
  868. $qb->expr()->isNull('node.'.$config['root']) :
  869. $qb->expr()->eq('node.'.$config['root'], is_string($rootId) ? $qb->expr()->literal($rootId) : $rootId)
  870. );
  871. }
  872. $nodes = $qb->getQuery()->getResult(Query::HYDRATE_OBJECT);
  873. foreach ($nodes as $node) {
  874. $right = $meta->getReflectionProperty($config['right'])->getValue($node);
  875. $left = $meta->getReflectionProperty($config['left'])->getValue($node);
  876. $id = $meta->getReflectionProperty($identifier)->getValue($node);
  877. $parent = $meta->getReflectionProperty($config['parent'])->getValue($node);
  878. if (!$right || !$left) {
  879. $errors[] = "node [{$id}] has invalid left or right values";
  880. } elseif ($right == $left) {
  881. $errors[] = "node [{$id}] has identical left and right values";
  882. } elseif ($parent) {
  883. if ($parent instanceof Proxy && !$parent->__isInitialized__) {
  884. $this->_em->refresh($parent);
  885. }
  886. $parentRight = $meta->getReflectionProperty($config['right'])->getValue($parent);
  887. $parentLeft = $meta->getReflectionProperty($config['left'])->getValue($parent);
  888. $parentId = $meta->getReflectionProperty($identifier)->getValue($parent);
  889. if ($left < $parentLeft) {
  890. $errors[] = "node [{$id}] left is less than parent`s [{$parentId}] left value";
  891. } elseif ($right > $parentRight) {
  892. $errors[] = "node [{$id}] right is greater than parent`s [{$parentId}] right value";
  893. }
  894. } else {
  895. $qb = $this->_em->createQueryBuilder();
  896. $qb->select($qb->expr()->count('node.'.$identifier))
  897. ->from($config['useObjectClass'], 'node')
  898. ->where($qb->expr()->lt('node.'.$config['left'], $left))
  899. ->andWhere($qb->expr()->gt('node.'.$config['right'], $right))
  900. ;
  901. if (isset($config['root'])) {
  902. $qb->andWhere($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. if ($count = intval($qb->getQuery()->getSingleScalarResult())) {
  908. $errors[] = "node [{$id}] parent field is blank, but it has a parent";
  909. }
  910. }
  911. }
  912. }
  913. /**
  914. * Removes single node without touching children
  915. *
  916. * @internal
  917. * @param EntityWrapper $wrapped
  918. * @return void
  919. */
  920. private function removeSingle(EntityWrapper $wrapped)
  921. {
  922. $meta = $this->getClassMetadata();
  923. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  924. $pk = $meta->getSingleIdentifierFieldName();
  925. $nodeId = $wrapped->getIdentifier();
  926. // prevent from deleting whole branch
  927. $qb = $this->_em->createQueryBuilder();
  928. $qb->update($config['useObjectClass'], 'node')
  929. ->set('node.'.$config['left'], 0)
  930. ->set('node.'.$config['right'], 0)
  931. ->where($nodeId === null ?
  932. $qb->expr()->isNull('node.'.$pk) :
  933. $qb->expr()->eq('node.'.$pk, is_string($nodeId) ? $qb->expr()->literal($nodeId) : $nodeId)
  934. )
  935. ;
  936. $qb->getQuery()->getSingleScalarResult();
  937. // remove the node from database
  938. $qb = $this->_em->createQueryBuilder();
  939. $qb->delete($config['useObjectClass'], 'node')
  940. ->where($nodeId === null ?
  941. $qb->expr()->isNull('node.'.$pk) :
  942. $qb->expr()->eq('node.'.$pk, is_string($nodeId) ? $qb->expr()->literal($nodeId) : $nodeId)
  943. )
  944. ;
  945. $qb->getQuery()->getSingleScalarResult();
  946. // remove from identity map
  947. $this->_em->getUnitOfWork()->removeFromIdentityMap($wrapped->getObject());
  948. }
  949. }