ClosureTreeRepository.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. <?php
  2. namespace Gedmo\Tree\Entity\Repository;
  3. use Gedmo\Exception\InvalidArgumentException;
  4. use Doctrine\ORM\Query;
  5. use Gedmo\Tree\Strategy;
  6. use Gedmo\Tree\Strategy\ORM\Closure;
  7. use Doctrine\ORM\Proxy\Proxy;
  8. /**
  9. * The ClosureTreeRepository has some useful functions
  10. * to interact with Closure tree. Repository uses
  11. * the strategy used by listener
  12. *
  13. * @author Gustavo Adrian <comfortablynumb84@gmail.com>
  14. * @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
  15. * @package Gedmo.Tree.Entity.Repository
  16. * @subpackage ClosureRepository
  17. * @link http://www.gediminasm.org
  18. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  19. */
  20. class ClosureTreeRepository extends AbstractTreeRepository
  21. {
  22. /**
  23. * Get all root nodes query
  24. *
  25. * @return Query
  26. */
  27. public function getRootNodesQuery()
  28. {
  29. $meta = $this->getClassMetadata();
  30. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  31. $qb = $this->_em->createQueryBuilder();
  32. $qb->select('node')
  33. ->from($config['useObjectClass'], 'node')
  34. ->where('node.' . $config['parent'] . " IS NULL");
  35. return $qb->getQuery();
  36. }
  37. /**
  38. * Get all root nodes
  39. *
  40. * @return array
  41. */
  42. public function getRootNodes()
  43. {
  44. return $this->getRootNodesQuery()->getResult();
  45. }
  46. /**
  47. * Counts the children of given TreeNode
  48. *
  49. * @param object $node - if null counts all records in tree
  50. * @param boolean $direct - true to count only direct children
  51. * @throws InvalidArgumentException - if input is not valid
  52. * @return integer
  53. */
  54. public function childCount($node = null, $direct = false)
  55. {
  56. $count = 0;
  57. $meta = $this->getClassMetadata();
  58. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  59. if (null !== $node) {
  60. if ($node instanceof $meta->name) {
  61. if (!$this->_em->getUnitOfWork()->isInIdentityMap($node)) {
  62. throw new InvalidArgumentException("Node is not managed by UnitOfWork");
  63. }
  64. if ($direct) {
  65. $qb = $this->_em->createQueryBuilder();
  66. $qb->select('COUNT(node)')
  67. ->from($config['useObjectClass'], 'node')
  68. ->where('node.' . $config['parent'] . ' = :node');
  69. $q = $qb->getQuery();
  70. } else {
  71. $closureMeta = $this->_em->getClassMetadata($config['closure']);
  72. $dql = "SELECT COUNT(c) FROM {$closureMeta->name} c";
  73. $dql .= " WHERE c.ancestor = :node";
  74. $dql .= " AND c.descendant <> :node";
  75. $q = $this->_em->createQuery($dql);
  76. }
  77. $q->setParameters(compact('node'));
  78. $count = intval($q->getSingleScalarResult());
  79. } else {
  80. throw new InvalidArgumentException("Node is not related to this repository");
  81. }
  82. } else {
  83. $dql = "SELECT COUNT(node) FROM " . $config['useObjectClass'] . " node";
  84. if ($direct) {
  85. $dql .= ' WHERE node.' . $config['parent'] . ' IS NULL';
  86. }
  87. $q = $this->_em->createQuery($dql);
  88. $count = intval($q->getSingleScalarResult());
  89. }
  90. return $count;
  91. }
  92. /**
  93. * Get the Tree path query by given $node
  94. *
  95. * @param object $node
  96. * @throws InvalidArgumentException - if input is not valid
  97. * @return Query
  98. */
  99. public function getPathQuery($node)
  100. {
  101. $meta = $this->getClassMetadata();
  102. if (!$node instanceof $meta->name) {
  103. throw new InvalidArgumentException("Node is not related to this repository");
  104. }
  105. if (!$this->_em->getUnitOfWork()->isInIdentityMap($node)) {
  106. throw new InvalidArgumentException("Node is not managed by UnitOfWork");
  107. }
  108. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  109. $closureMeta = $this->_em->getClassMetadata($config['closure']);
  110. $dql = "SELECT c, node FROM {$closureMeta->name} c";
  111. $dql .= " INNER JOIN c.ancestor node";
  112. $dql .= " WHERE c.descendant = :node";
  113. $dql .= " ORDER BY c.depth DESC";
  114. $q = $this->_em->createQuery($dql);
  115. $q->setParameters(compact('node'));
  116. return $q;
  117. }
  118. /**
  119. * Get the Tree path of Nodes by given $node
  120. *
  121. * @param object $node
  122. * @return array - list of Nodes in path
  123. */
  124. public function getPath($node)
  125. {
  126. return array_map(function($closure) {
  127. return $closure->getAncestor();
  128. }, $this->getPathQuery($node)->getResult());
  129. }
  130. /**
  131. * Get tree children query followed by given $node
  132. *
  133. * @param object $node - if null, all tree nodes will be taken
  134. * @param boolean $direct - true to take only direct children
  135. * @param string $sortByField - field name to sort by
  136. * @param string $direction - sort direction : "ASC" or "DESC"
  137. * @throws InvalidArgumentException - if input is not valid
  138. * @return Query
  139. */
  140. public function childrenQuery($node = null, $direct = false, $sortByField = null, $direction = 'ASC')
  141. {
  142. $meta = $this->getClassMetadata();
  143. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  144. $qb = $this->_em->createQueryBuilder();
  145. if ($node !== null) {
  146. if ($node instanceof $meta->name) {
  147. if (!$this->_em->getUnitOfWork()->isInIdentityMap($node)) {
  148. throw new InvalidArgumentException("Node is not managed by UnitOfWork");
  149. }
  150. $qb->select('c, node')
  151. ->from($config['closure'], 'c')
  152. ->innerJoin('c.descendant', 'node')
  153. ->where('c.ancestor = :node');
  154. if ($direct) {
  155. $qb->andWhere('c.depth = 1');
  156. } else {
  157. $qb->andWhere('c.descendant <> :node');
  158. }
  159. } else {
  160. throw new \InvalidArgumentException("Node is not related to this repository");
  161. }
  162. } else {
  163. $qb->select('node')
  164. ->from($config['useObjectClass'], 'node');
  165. if ($direct) {
  166. $qb->where('node.' . $config['parent'] . ' IS NULL');
  167. }
  168. }
  169. if ($sortByField) {
  170. if ($meta->hasField($sortByField) && in_array(strtolower($direction), array('asc', 'desc'))) {
  171. $qb->orderBy('node.' . $sortByField, $direction);
  172. } else {
  173. throw new InvalidArgumentException("Invalid sort options specified: field - {$sortByField}, direction - {$direction}");
  174. }
  175. }
  176. $q = $qb->getQuery();
  177. if ($node) {
  178. $q->setParameters(compact('node'));
  179. }
  180. return $q;
  181. }
  182. /**
  183. * Get list of children followed by given $node
  184. *
  185. * @param object $node - if null, all tree nodes will be taken
  186. * @param boolean $direct - true to take only direct children
  187. * @param string $sortByField - field name to sort by
  188. * @param string $direction - sort direction : "ASC" or "DESC"
  189. * @return array - list of given $node children, null on failure
  190. */
  191. public function children($node = null, $direct = false, $sortByField = null, $direction = 'ASC')
  192. {
  193. $result = $this->childrenQuery($node, $direct, $sortByField, $direction)->getResult();
  194. if ($node) {
  195. $result = array_map(function($closure) {
  196. return $closure->getDescendant();
  197. }, $result);
  198. }
  199. return $result;
  200. }
  201. /**
  202. * Removes given $node from the tree and reparents its descendants
  203. *
  204. * @todo: may be improved, to issue single query on reparenting
  205. * @param object $node
  206. * @throws RuntimeException - if something fails in transaction
  207. * @return void
  208. */
  209. public function removeFromTree($node)
  210. {
  211. $meta = $this->getClassMetadata();
  212. if (!$node instanceof $meta->name) {
  213. throw new InvalidArgumentException("Node is not related to this repository");
  214. }
  215. if (!$this->_em->getUnitOfWork()->isInIdentityMap($node)) {
  216. throw new InvalidArgumentException("Node is not managed by UnitOfWork");
  217. }
  218. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  219. $pk = $meta->getSingleIdentifierFieldName();
  220. $nodeId = $meta->getReflectionProperty($pk)->getValue($node);
  221. $parent = $meta->getReflectionProperty($config['parent'])->getValue($node);
  222. $dql = "SELECT node FROM {$config['useObjectClass']} node";
  223. $dql .= " WHERE node.{$config['parent']} = :node";
  224. $q = $this->_em->createQuery($dql);
  225. $q->setParameters(compact('node'));
  226. $nodesToReparent = $q->getResult();
  227. // process updates in transaction
  228. $this->_em->getConnection()->beginTransaction();
  229. try {
  230. foreach ($nodesToReparent as $nodeToReparent) {
  231. $id = $meta->getReflectionProperty($pk)->getValue($nodeToReparent);
  232. $meta->getReflectionProperty($config['parent'])->setValue($nodeToReparent, $parent);
  233. $dql = "UPDATE {$config['useObjectClass']} node";
  234. $dql .= " SET node.{$config['parent']} = :parent";
  235. $dql .= " WHERE node.{$pk} = :id";
  236. $q = $this->_em->createQuery($dql);
  237. $q->setParameters(compact('parent', 'id'));
  238. $q->getSingleScalarResult();
  239. $this->listener
  240. ->getStrategy($this->_em, $meta->name)
  241. ->updateNode($this->_em, $nodeToReparent, $node);
  242. $oid = spl_object_hash($nodeToReparent);
  243. $this->_em->getUnitOfWork()->setOriginalEntityProperty($oid, $config['parent'], $parent);
  244. }
  245. $dql = "DELETE {$config['useObjectClass']} node";
  246. $dql .= " WHERE node.{$pk} = :nodeId";
  247. $q = $this->_em->createQuery($dql);
  248. $q->setParameters(compact('nodeId'));
  249. $q->getSingleScalarResult();
  250. $this->_em->getConnection()->commit();
  251. } catch (\Exception $e) {
  252. $this->_em->close();
  253. $this->_em->getConnection()->rollback();
  254. throw new \Gedmo\Exception\RuntimeException('Transaction failed', null, $e);
  255. }
  256. // remove from identity map
  257. $this->_em->getUnitOfWork()->removeFromIdentityMap($node);
  258. $node = null;
  259. }
  260. /**
  261. * {@inheritdoc}
  262. */
  263. protected function validates()
  264. {
  265. return $this->listener->getStrategy($this->_em, $this->getClassMetadata()->name)->getName() === Strategy::CLOSURE;
  266. }
  267. }