NestedTreeRepository.php 43 KB

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