ClosureTreeRepository.php 14 KB

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