Closure.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. <?php
  2. namespace Gedmo\Tree\Strategy\ORM;
  3. use Gedmo\Tree\Strategy,
  4. Doctrine\ORM\EntityManager,
  5. Doctrine\ORM\Proxy\Proxy,
  6. Gedmo\Tree\AbstractTreeListener;
  7. /**
  8. * This strategy makes tree act like
  9. * a closure table.
  10. *
  11. * Some Tree logic is copied from -
  12. * CakePHP: Rapid Development Framework (http://cakephp.org)
  13. *
  14. * @author Gustavo Adrian <comfortablynumb84@gmail.com>
  15. * @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
  16. * @package Gedmo.Tree.Strategy.ORM
  17. * @subpackage Closure
  18. * @link http://www.gediminasm.org
  19. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  20. */
  21. class Closure implements Strategy
  22. {
  23. /**
  24. * TreeListener
  25. *
  26. * @var AbstractTreeListener
  27. */
  28. protected $listener = null;
  29. /**
  30. * List of pending Nodes, which needs to
  31. * be post processed because of having a parent Node
  32. * which requires some additional calculations
  33. *
  34. * @var array
  35. */
  36. protected $pendingChildNodeInserts = array();
  37. /**
  38. * List of pending Nodes to remove
  39. *
  40. * @var array
  41. */
  42. protected $pendingNodesForRemove = array();
  43. /**
  44. * {@inheritdoc}
  45. */
  46. public function __construct(AbstractTreeListener $listener)
  47. {
  48. $this->listener = $listener;
  49. }
  50. /**
  51. * {@inheritdoc}
  52. */
  53. public function getName()
  54. {
  55. return Strategy::CLOSURE;
  56. }
  57. /**
  58. * {@inheritdoc}
  59. */
  60. public function processPrePersist($em, $entity)
  61. {
  62. $this->pendingChildNodeInserts[] = $entity;
  63. }
  64. /**
  65. * {@inheritdoc}
  66. */
  67. public function processPostPersist($em, $entity)
  68. {
  69. if (count($this->pendingChildNodeInserts)) {
  70. while ($e = array_shift($this->pendingChildNodeInserts))
  71. {
  72. $this->insertNode($em, $e);
  73. }
  74. // If "childCount" property is in the schema, we recalculate child count of all entities
  75. $meta = $em->getClassMetadata(get_class($entity));
  76. $config = $this->listener->getConfiguration($em, $meta->name);
  77. if (isset($config['childCount'])) {
  78. $this->recalculateChildCountForEntities($em, get_class( $entity ));
  79. }
  80. }
  81. }
  82. public function insertNode(EntityManager $em, $entity, $addNodeChildrenToAncestors = false)
  83. {
  84. $meta = $em->getClassMetadata(get_class($entity));
  85. $config = $this->listener->getConfiguration($em, $meta->name);
  86. $identifier = $meta->getSingleIdentifierFieldName();
  87. $id = $this->extractIdentifier( $em, $entity );
  88. $closureMeta = $em->getClassMetadata($config['closure']);
  89. $entityTable = $meta->getTableName();
  90. $closureTable = $closureMeta->getTableName();
  91. $entries = array();
  92. $childrenIDs = array();
  93. $ancestorsIDs = array();
  94. // If node has children it means it already has a self referencing row, so we skip its insertion
  95. if ($addNodeChildrenToAncestors === false) {
  96. $entries[] = array(
  97. 'ancestor' => $id,
  98. 'descendant' => $id,
  99. 'depth' => 0
  100. );
  101. }
  102. $parent = $meta->getReflectionProperty($config['parent'])->getValue($entity);
  103. if ( $parent ) {
  104. $parentId = $meta->getReflectionProperty($identifier)->getValue($parent);
  105. $dql = "SELECT c.ancestor, c.depth FROM {$closureMeta->name} c";
  106. $dql .= " WHERE c.descendant = {$parentId}";
  107. $ancestors = $em->createQuery($dql)->getArrayResult();
  108. foreach ($ancestors as $ancestor) {
  109. $entries[] = array(
  110. 'ancestor' => $ancestor['ancestor'],
  111. 'descendant' => $id,
  112. 'depth' => $ancestor['depth'] + 1
  113. );
  114. $ancestorsIDs[] = $ancestor['ancestor'];
  115. if ($addNodeChildrenToAncestors === true) {
  116. $dql = "SELECT c.descendant, c.depth FROM {$closureMeta->name} c";
  117. $dql .= " WHERE c.ancestor = {$id} AND c.ancestor != c.descendant";
  118. $children = $em->createQuery($dql)
  119. ->getArrayResult();
  120. foreach ($children as $child)
  121. {
  122. $entries[] = array(
  123. 'ancestor' => $ancestor['ancestor'],
  124. 'descendant' => $child['descendant'],
  125. 'depth' => $child['depth'] + 1
  126. );
  127. $childrenIDs[] = $child['descendant'];
  128. }
  129. }
  130. }
  131. }
  132. foreach ($entries as $closure) {
  133. if (!$em->getConnection()->insert($closureTable, $closure)) {
  134. throw new \Gedmo\Exception\RuntimeException('Failed to insert new Closure record');
  135. }
  136. }
  137. }
  138. /**
  139. * {@inheritdoc}
  140. */
  141. public function processScheduledUpdate($em, $entity)
  142. {
  143. $entityClass = get_class($entity);
  144. $config = $this->listener->getConfiguration($em, $entityClass);
  145. $meta = $em->getClassMetadata($entityClass);
  146. $uow = $em->getUnitOfWork();
  147. $changeSet = $uow->getEntityChangeSet($entity);
  148. if (array_key_exists($config['parent'], $changeSet)) {
  149. $this->updateNode($em, $entity, $changeSet[$config['parent']]);
  150. }
  151. // If "childCount" property is in the schema, we recalculate child count of all entities
  152. if (isset($config['childCount'])) {
  153. $this->recalculateChildCountForEntities($em, get_class( $entity ));
  154. }
  155. }
  156. public function updateNode(EntityManager $em, $entity, array $change)
  157. {
  158. $meta = $em->getClassMetadata(get_class($entity));
  159. $config = $this->listener->getConfiguration($em, $meta->name);
  160. $closureMeta = $em->getClassMetadata($config['closure']);
  161. $oldParent = $change[0];
  162. $nodeId = $this->extractIdentifier($em, $entity);
  163. $table = $closureMeta->getTableName();
  164. if ($oldParent) {
  165. $this->removeClosurePathsOfNodeID($em, $table, $nodeId);
  166. $this->insertNode($em, $entity, true);
  167. }
  168. //\Doctrine\Common\Util\Debug::dump($oldParent);
  169. //die();
  170. }
  171. /**
  172. * {@inheritdoc}
  173. */
  174. public function processScheduledDelete($em, $entity)
  175. {
  176. $this->removeNode($em, $entity);
  177. // If "childCount" property is in the schema, we recalculate child count of all entities
  178. $meta = $em->getClassMetadata(get_class($entity));
  179. $config = $this->listener->getConfiguration($em, $meta->name);
  180. if (isset($config['childCount'])) {
  181. $this->recalculateChildCountForEntities($em, get_class( $entity ));
  182. }
  183. }
  184. public function removeNode(EntityManager $em, $entity, $maintainSelfReferencingRow = false, $maintainSelfReferencingRowOfChildren = false)
  185. {
  186. $meta = $em->getClassMetadata(get_class($entity));
  187. $config = $this->listener->getConfiguration($em, $meta->name);
  188. $closureMeta = $em->getClassMetadata($config['closure']);
  189. $id = $this->extractIdentifier( $em, $entity );
  190. $this->removeClosurePathsOfNodeID($em, $closureMeta->getTableName(), $id, $maintainSelfReferencingRow, $maintainSelfReferencingRowOfChildren);
  191. }
  192. public function removeClosurePathsOfNodeID(EntityManager $em, $table, $nodeId, $maintainSelfReferencingRow = true, $maintainSelfReferencingRowOfChildren = true)
  193. {
  194. $subquery = "SELECT c1.id FROM {$table} c1 ";
  195. $subquery .= "WHERE c1.descendant IN ( SELECT c2.descendant FROM {$table} c2 WHERE c2.ancestor = :id ) ";
  196. $subquery .= "AND ( c1.ancestor IN ( SELECT c3.ancestor FROM {$table} c3 WHERE c3.descendant = :id ";
  197. if ($maintainSelfReferencingRow === true)
  198. {
  199. $subquery .= "AND c3.descendant != c3.ancestor ";
  200. }
  201. if ( $maintainSelfReferencingRowOfChildren === false )
  202. {
  203. $subquery .= " OR c1.descendant = c1.ancestor ";
  204. }
  205. $subquery .= " ) ) ";
  206. $subquery = "DELETE FROM {$table} WHERE {$table}.id IN ( SELECT temp_table.id FROM ( {$subquery} ) temp_table )";
  207. if (!$em->getConnection()->executeQuery($subquery, array('id' => $nodeId))) {
  208. throw new \Gedmo\Exception\RuntimeException('Failed to delete old Closure records');
  209. }
  210. }
  211. public function recalculateChildCountForEntities($em, $entityClass)
  212. {
  213. $meta = $em->getClassMetadata($entityClass);
  214. $config = $this->listener->getConfiguration($em, $meta->name);
  215. $entityIdentifierField = $meta->getIdentifierColumnNames();
  216. $entityIdentifierField = $entityIdentifierField[ 0 ];
  217. $childCountField = $config['childCount'];
  218. $closureMeta = $em->getClassMetadata($config['closure']);
  219. $entityTable = $meta->getTableName();
  220. $closureTable = $closureMeta->getTableName();
  221. $subquery = "( SELECT COUNT( c2.descendant ) FROM {$closureTable} c2 WHERE c2.ancestor = c1.{$entityIdentifierField} AND c2.ancestor != c2.descendant )";
  222. $sql = "UPDATE {$entityTable} c1 SET c1.{$childCountField} = {$subquery}";
  223. if (!$em->getConnection()->executeQuery($sql)) {
  224. throw new \Gedmo\Exception\RuntimeException('Failed to update child count field of entities');
  225. }
  226. }
  227. private function extractIdentifier($em, $entity, $single = true)
  228. {
  229. if ($entity instanceof Proxy) {
  230. $id = $em->getUnitOfWork()->getEntityIdentifier($entity);
  231. } else {
  232. $meta = $em->getClassMetadata(get_class($entity));
  233. $id = array();
  234. foreach ($meta->identifier as $name) {
  235. $id[$name] = $meta->getReflectionProperty($name)->getValue($entity);
  236. }
  237. }
  238. if ($single) {
  239. $id = current($id);
  240. }
  241. return $id;
  242. }
  243. /**
  244. * {@inheritdoc}
  245. */
  246. public function onFlushEnd($em)
  247. {}
  248. }