ClosureTreeRepository.php 14 KB

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