NestedTreeRepository.php 43 KB

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