ClosureTreeRepository.php 11 KB

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