ClosureTreeRepository.php 16 KB

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