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