ClosureTreeRepository.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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. * @param bool $includeNode - Include the root node in the result?
  141. *
  142. * @throws InvalidArgumentException - if input is not valid
  143. * @return Query
  144. */
  145. public function childrenQueryBuilder($node = null, $direct = false, $sortByField = null, $direction = 'ASC', $includeNode = false)
  146. {
  147. $meta = $this->getClassMetadata();
  148. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  149. $qb = $this->_em->createQueryBuilder();
  150. if ($node !== null) {
  151. if ($node instanceof $meta->name) {
  152. if (!$this->_em->getUnitOfWork()->isInIdentityMap($node)) {
  153. throw new InvalidArgumentException("Node is not managed by UnitOfWork");
  154. }
  155. $where = 'c.ancestor = :node AND ';
  156. $qb->select('c, node')
  157. ->from($config['closure'], 'c')
  158. ->innerJoin('c.descendant', 'node');
  159. if ($direct) {
  160. $where .= 'c.depth = 1';
  161. } else {
  162. $where .= 'c.descendant <> :node';
  163. }
  164. $qb->where($where);
  165. if ($includeNode) {
  166. $qb->orWhere('c.ancestor = :node AND c.descendant = :node');
  167. }
  168. } else {
  169. throw new \InvalidArgumentException("Node is not related to this repository");
  170. }
  171. } else {
  172. $qb->select('node')
  173. ->from($config['useObjectClass'], 'node');
  174. if ($direct) {
  175. $qb->where('node.' . $config['parent'] . ' IS NULL');
  176. }
  177. }
  178. if ($sortByField) {
  179. if ($meta->hasField($sortByField) && in_array(strtolower($direction), array('asc', 'desc'))) {
  180. $qb->orderBy('node.' . $sortByField, $direction);
  181. } else {
  182. throw new InvalidArgumentException("Invalid sort options specified: field - {$sortByField}, direction - {$direction}");
  183. }
  184. }
  185. if ($node) {
  186. $qb->setParameter('node', $node);
  187. }
  188. return $qb;
  189. }
  190. public function childrenQuery($node = null, $direct = false, $sortByField = null, $direction = 'ASC', $includeNode = false)
  191. {
  192. return $this->childrenQueryBuilder($node, $direct, $sortByField, $direction, $includeNode)->getQuery();
  193. }
  194. /**
  195. * Get list of children followed by given $node
  196. *
  197. * @param object $node - if null, all tree nodes will be taken
  198. * @param boolean $direct - true to take only direct children
  199. * @param string $sortByField - field name to sort by
  200. * @param string $direction - sort direction : "ASC" or "DESC"
  201. * @param bool $includeNode - Include the root node in results?
  202. * @return array - list of given $node children, null on failure
  203. */
  204. public function children($node = null, $direct = false, $sortByField = null, $direction = 'ASC', $includeNode = false)
  205. {
  206. $result = $this->childrenQuery($node, $direct, $sortByField, $direction, $includeNode)->getResult();
  207. if ($node) {
  208. $result = array_map(function($closure) {
  209. return $closure->getDescendant();
  210. }, $result);
  211. }
  212. return $result;
  213. }
  214. /**
  215. * Removes given $node from the tree and reparents its descendants
  216. *
  217. * @todo: may be improved, to issue single query on reparenting
  218. * @param object $node
  219. * @throws RuntimeException - if something fails in transaction
  220. * @return void
  221. */
  222. public function removeFromTree($node)
  223. {
  224. $meta = $this->getClassMetadata();
  225. if (!$node instanceof $meta->name) {
  226. throw new InvalidArgumentException("Node is not related to this repository");
  227. }
  228. $wrapped = new EntityWrapper($node, $this->_em);
  229. if (!$wrapped->hasValidIdentifier()) {
  230. throw new InvalidArgumentException("Node is not managed by UnitOfWork");
  231. }
  232. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  233. $pk = $meta->getSingleIdentifierFieldName();
  234. $nodeId = $wrapped->getIdentifier();
  235. $parent = $wrapped->getPropertyValue($config['parent']);
  236. $dql = "SELECT node FROM {$config['useObjectClass']} node";
  237. $dql .= " WHERE node.{$config['parent']} = :node";
  238. $q = $this->_em->createQuery($dql);
  239. $q->setParameters(compact('node'));
  240. $nodesToReparent = $q->getResult();
  241. // process updates in transaction
  242. $this->_em->getConnection()->beginTransaction();
  243. try {
  244. foreach ($nodesToReparent as $nodeToReparent) {
  245. $id = $meta->getReflectionProperty($pk)->getValue($nodeToReparent);
  246. $meta->getReflectionProperty($config['parent'])->setValue($nodeToReparent, $parent);
  247. $dql = "UPDATE {$config['useObjectClass']} node";
  248. $dql .= " SET node.{$config['parent']} = :parent";
  249. $dql .= " WHERE node.{$pk} = :id";
  250. $q = $this->_em->createQuery($dql);
  251. $q->setParameters(compact('parent', 'id'));
  252. $q->getSingleScalarResult();
  253. $this->listener
  254. ->getStrategy($this->_em, $meta->name)
  255. ->updateNode($this->_em, $nodeToReparent, $node);
  256. $oid = spl_object_hash($nodeToReparent);
  257. $this->_em->getUnitOfWork()->setOriginalEntityProperty($oid, $config['parent'], $parent);
  258. }
  259. $dql = "DELETE {$config['useObjectClass']} node";
  260. $dql .= " WHERE node.{$pk} = :nodeId";
  261. $q = $this->_em->createQuery($dql);
  262. $q->setParameters(compact('nodeId'));
  263. $q->getSingleScalarResult();
  264. $this->_em->getConnection()->commit();
  265. } catch (\Exception $e) {
  266. $this->_em->close();
  267. $this->_em->getConnection()->rollback();
  268. throw new \Gedmo\Exception\RuntimeException('Transaction failed: '.$e->getMessage(), null, $e);
  269. }
  270. // remove from identity map
  271. $this->_em->getUnitOfWork()->removeFromIdentityMap($node);
  272. $node = null;
  273. }
  274. /**
  275. * Process nodes and produce an array with the
  276. * structure of the tree
  277. *
  278. * @param array - Array of nodes
  279. *
  280. * @return array - Array with tree structure
  281. */
  282. public function buildTreeArray(array $nodes)
  283. {
  284. $meta = $this->getClassMetadata();
  285. $config = $this->listener->getConfiguration($this->_em, $meta->name);
  286. $nestedTree = array();
  287. $idField = $meta->getSingleIdentifierFieldName();
  288. $hasLevelProp = !empty($config['level']);
  289. $levelProp = $hasLevelProp ? $config['level'] : self::SUBQUERY_LEVEL;
  290. if (count($nodes) > 0) {
  291. $l = 1;
  292. $refs = array();
  293. foreach ($nodes as $n) {
  294. $node = $n[0]['descendant'];
  295. $node['__children'] = array();
  296. $level = $hasLevelProp ? $node[$levelProp] : $n[$levelProp];
  297. if ($l < $level) {
  298. $l = $level;
  299. }
  300. if ($l == 1) {
  301. $tmp = &$nestedTree;
  302. } else {
  303. $tmp = &$refs[$n['parent_id']]['__children'];
  304. }
  305. $key = count($tmp);
  306. $tmp[$key] = $node;
  307. $refs[$node[$idField]] = &$tmp[$key];
  308. }
  309. unset($refs);
  310. }
  311. return $nestedTree;
  312. }
  313. /**
  314. * {@inheritdoc}
  315. */
  316. public function getNodesHierarchy($node, $direct, array $config, array $options = array())
  317. {
  318. return $this->getNodesHierarchyQuery($node, $direct, $config, $options)->getArrayResult();
  319. }
  320. /**
  321. * {@inheritdoc}
  322. */
  323. public function getNodesHierarchyQuery($node, $direct, array $config, array $options = array())
  324. {
  325. return $this->getNodesHierarchyQueryBuilder($node, $direct, $config, $options)->getQuery();
  326. }
  327. /**
  328. * {@inheritdoc}
  329. */
  330. public function getNodesHierarchyQueryBuilder($node, $direct, array $config, array $options = array())
  331. {
  332. $meta = $this->getClassMetadata();
  333. $idField = $meta->getSingleIdentifierFieldName();
  334. $subQuery = '';
  335. $hasLevelProp = isset($config['level']) && $config['level'];
  336. if (!$hasLevelProp) {
  337. $subQuery = ', (SELECT MAX(c2.depth) + 1 FROM '.$config['closure'];
  338. $subQuery .= ' c2 WHERE c2.descendant = c.descendant GROUP BY c2.descendant) AS '.self::SUBQUERY_LEVEL;
  339. }
  340. $q = $this->_em->createQueryBuilder()
  341. ->select('c, node, p.'.$idField.' AS parent_id'.$subQuery)
  342. ->from($config['closure'], 'c')
  343. ->innerJoin('c.descendant', 'node')
  344. ->leftJoin('node.parent', 'p')
  345. ->where('c.ancestor = :node')
  346. ->addOrderBy(($hasLevelProp ? 'node.'.$config['level'] : self::SUBQUERY_LEVEL), 'asc');
  347. $defaultOptions = array();
  348. $options = array_merge($defaultOptions, $options);
  349. if (isset($options['childSort']) && is_array($options['childSort']) &&
  350. isset($options['childSort']['field']) && isset($options['childSort']['dir'])) {
  351. $q->addOrderBy(
  352. 'node.'.$options['childSort']['field'],
  353. strtolower($options['childSort']['dir']) == 'asc' ? 'asc' : 'desc'
  354. );
  355. }
  356. $q->setParameters(compact('node'));
  357. return $q;
  358. }
  359. /**
  360. * {@inheritdoc}
  361. */
  362. protected function validate()
  363. {
  364. return $this->listener->getStrategy($this->_em, $this->getClassMetadata()->name)->getName() === Strategy::CLOSURE;
  365. }
  366. }